Riska Nanda
Riska Nanda

Reputation: 129

How to make a loop for each sentence

I have a dictionary program, but have a problem when output results, I want the results of each sentence.

dict_file = """water=45 
melon=8 
apple=35 
pineapple=67 
I=43 
to=90 
eat=12 
tastes=100 
sweet=21 
it=80 
watermelon=98 
want=70
juice=88"""

conversion = {k: int(v) for line in dict_file.split('\n') for (k,v) in (line.split('='),)}

text = """I want to eat banana and watermelon
I want drink juice purple and pineapple
it tastes sweet pineapple"""

result= ', '.join(str(conversion[word]) for word in text.split() if word in conversion)

print(result)

Output :

43, 70, 90, 12, 98, 43, 70, 88, 67, 80, 100, 21, 67

I want to output :

43, 70, 90, 12, 98
43, 70, 88, 67
80, 100, 21, 67

Upvotes: 0

Views: 88

Answers (2)

Steven Rumbalski
Steven Rumbalski

Reputation: 45542

text.split() splits on all whitespace, obliterating your newlines. First split on newlines ('\n') then split on any remaining whitespace. Rejoin what you split on whitespace with commas. Rejoin what you split with newlines with newlines.

result = '\n'.join(
    ', '.join(str(conversion[word]) for word in line.split() if word in conversion) 
    for line in text.split('\n'))

You could change str(conversion[word]) to conversion[word] if you change the definition of conversion:

# replaced int(v) with v.strip()
conversion = {k: v.strip() for line in dict_file.split('\n') for (k,v) in (line.split('='),)}

I would prefer this definition:

conversion = dict(line.strip().split('=') for line in dict_file.split('\n'))

Here's a variation that handles missing values differently:

result = '\n'.join(
    ', '.join(conversion.get(word, '--') for word in line.split())
    for line in text.split('\n'))

print(result) gives

43, 70, 90, 12, --, --, 98
43, 70, --, 88, --, --, 67
80, 100, 21, 67

Upvotes: 2

SparkAndShine
SparkAndShine

Reputation: 18007

Personally, readability is more important than brevity.

for line in text.split('\n'):
    s = ', '.join(str(conversion[word]) for word in line.split() if word in conversion)
    print(s)

# Output
'''
43, 70, 90, 12, 98
43, 70, 88, 67
80, 100, 21, 67
'''

Upvotes: 0

Related Questions