Python:从单词列表中创建一个句子(逗号和句点前不应有空格)

2024-05-02 21:43:35 发布

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

想要的输出:如果没有人爱他,他可能会努力去爱自己

words = ["if", "nobody", "loved", "him", ",", "he", "probably", "struggled", "to", "love", "himself", "."]

for i in range(len(words)):
    if words[i] == "." or ",":
        continue
    sentence = " ".join(words)

print(sentence.capitalize())

但是,它不起作用。如何在列表中找到逗号和句点


Tags: toinforifrangesentencehewords
3条回答

使用replace固定句点和逗号

words = ["if", "nobody", "loved", "him", ",", "he", "probably", "struggled", "to", "love", "himself", "."]

for i in range(len(words)):
    if words[i] == "." or ",":
        continue
sentence = (" ".join(words)).replace(' .','.').replace(' ,',',') # use replace to fix period and comma

print(sentence.capitalize())
If nobody loved him, he probably struggled to love himself.

您可以使用正则表达式,只需将不需要空格的字符放在括号[.,;]中,这样更容易处理新的情况,而且更短

import re
words = ["if", "nobody", "loved", "him", ",", "he", "probably", "struggled", "to", "love", "himself", "."]

sentence = re.sub(r"(?: ([.,;]))", r"\g<1>", " ".join(words))

print(sentence)

regex(?: ([.,;]))匹配一个空格,后跟括号内的一个字符,并仅替换为这个字符(不包括空格so)

首先,words[i] == "." or ","总是正确的。所以你总是进入continue,这就是你不能打印任何东西的原因。您应该将其更改为word == "." or word == ","

其次,您可以在循环中迭代单词

正确代码:

words = ["if", "nobody", "loved", "him", ",", "he", "probably", "struggled", "to", "love", "himself", "."]

sentence = ""
for word in words:
    if word == "." or word == ",":
        sentence += word
    else:
        sentence += " "
        sentence += word
print(sentence.strip().capitalize())

相关问题 更多 >