【发布时间】:2021-12-18 07:18:32
【问题描述】:
我有一个“爱丽丝梦游仙境”的 .txt 文件,需要去掉所有标点符号并使所有单词小写,这样我才能找到文件中唯一单词的数量。下面提到的wordlist 是书中所有单个单词作为字符串的列表,所以wordlist 看起来像这样
["Alice's", 'Adventures', 'in', 'Wonderland', "ALICE'S",
'ADVENTURES', 'IN', 'WONDERLAND', 'Lewis', 'Carroll', 'THE',
'MILLENNIUM', 'FULCRUM', 'EDITION', '3.0', 'CHAPTER', 'I',
'Down', 'the', 'Rabbit-Hole', 'Alice', 'was', 'beginning',
'to', 'get', 'very', 'tired', 'of', 'sitting', 'by', 'her',
'sister', 'on', 'the', 'bank,'
到目前为止我的解决方案代码是
from string import punctuation
def wordcount(book):
for word in wordlist:
no_punc = word.strip(punctuation)
lower_case = no_punc.lower()
newlist = lower_case.split()
print(newlist)
这适用于去除标点符号并使所有单词小写,但是newlist = lower_case.split() 会为每个单词创建一个单独的列表,因此我无法遍历一个大列表来查找唯一单词的数量。我这样做.split() 的原因是,当迭代时,python 不会将任何字母视为一个单词,而是每个单词都保持完整,因为它是它自己的列表项。关于如何改进这个或更有效的方法的任何想法?这是输出的示例
['down']
['the']
['rabbit-hole']
['alice']
['was']
['beginning']
['to']
['get']
['very']
['tired']
['of']
['sitting']
['by']
['her']
【问题讨论】:
标签: string list concatenation strip txt