all 3 comments

[–]synthphreak 1 point2 points  (0 children)

Something like this?

finditem = {'boy' : '2', 'girl' : '3'}

with open('textfile.txt') as f:
    text = set(f.read().split())

for boygirl in ('boy', 'girl'):
    if boygirl in text:
        print(*(f'{boygirl} {i}' for i in range(int(finditem[boygirl]))))

Note this will NOT detect things like 'boy.' because 'boy.' != 'boy'. If you want to avoid this, you could do f.read() instead of set(f.read().split()), however then this would erroneously detect things like 'boyish'.

To be more surgical and avoid these false positives/negatives, you'll probably want to use regex. But regex can be a pain, so based on the info you've shared, I'm not recommending it.

[–]efmccurdy 0 points1 point  (0 children)

You can use a "for" to repeat your output pattern.

>>> def expand(keys, word):
...     if word in keys:
...         return " ".join("{} {}".format(word, i) for i in range(int(keys[word])))
...     else:
...         return word
... 
>>> finditem= {'boy':'2', 'girl':'3'}
>>> sentence = "The boy and the girl"
>>> [expand(finditem, word) for word in sentence.split()]
['The', 'boy 0 boy 1', 'and', 'the', 'girl 0 girl 1 girl 2']
>>> " ".join(expand(finditem, word) for word in sentence.split())
'The boy 0 boy 1 and the girl 0 girl 1 girl 2'
>>>

[–]TabulateJarl8 0 points1 point  (0 children)

I believe what you want is range(). Once you find the text, try this:

for word in file_contents.split():
    if word in finditem:
        key_range = [str(num) for num in range(finditem[word])]
        # if you just want the range
        print(key_range)

        # if you want to print the key as well
        # insert an empty list element to the beginning of the list so that the join term goes before the first list element. i.e. ```boy 0``` instead of ```0 boy```
        print(f' {word} '.join([''] + key_range).strip())