【发布时间】:2018-09-28 06:49:57
【问题描述】:
下面的 python 代码将“resting-place”读作一个单词。
修改后的列表显示为:['This', 'is', 'my', 'resting-place.']
我希望它显示为:['This', 'is', 'my', 'resting', 'place']
因此,总共给了我 5 个单词,而不是修改后的列表中的 4 个单词。
original = 'This is my resting-place.'
modified = original.split()
print(modified)
numWords = 0
for word in modified:
numWords += 1
print ('Total words are:', numWords)
输出是:
Total words are: 4
我希望输出有 5 个单词。
【问题讨论】:
-
如果您想要的话,也可以在
'-'拆分...numWords = sum(len(word.split('-')) for word in modified) -
@mij contd from above comment: 所以,我想删除“-”并将 resting-place 读为两个词,而不是一个。
-
是的,您的字符串中的这些单词之间没有空格,但这无关紧要。该问题的最佳答案从字符串中删除空格和标点符号以仅给出单词,无论每个单词之间有多少。在您的字符串上使用该问题的答案,
re.findall(r"[\w']+", original)给出['This', 'is', 'my', 'resting', 'place']。
标签: python split counting strip word-count