如何为每个句子做一个循环

2024-10-02 00:19:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典程序,但是输出结果时有问题,我要每个句子的结果。你知道吗

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)

输出:

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

我想输出:

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

Tags: toinforitdictwordfilesplit
2条回答

就个人而言,可读性比简洁更重要。你知道吗

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
'''

text.split()所有空格上拆分,删除换行符。首先在换行符('\n')上拆分,然后在剩余的空白处拆分。用逗号重新连接你在空白处的内容。用换行符和换行符重新连接拆分的内容。你知道吗

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

如果更改conversion的定义,可以将str(conversion[word])更改为conversion[word]

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

我更喜欢这样的定义:

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

以下是一个不同的变体,它以不同的方式处理缺少的值:

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

print(result)给出

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

相关问题 更多 >

    热门问题