我的程序打开一个文件,它可以对其中包含的单词进行字数统计,但我想创建一个由文本中所有唯一单词组成的字典 例如,如果“计算机”这个词出现了三次,我希望它算作一个唯一的词
def main():
file = input('Enter the name of the input file: ')
infile = open(file, 'r')
file_contents = infile.read()
infile.close()
words = file_contents.split()
number_of_words = len(words)
print("There are", number_of_words, "words contained in this paragarph")
main()
请您参考如下方法:
使用一套。这将只包括独特的词:
words = set(words)
如果你不关心大小写,你可以这样做:
words = set(word.lower() for word in words)
这假设没有标点符号。如果有,您需要去除标点符号。
import string
words = set(word.lower().strip(string.punctuation) for word in words)
如果您需要跟踪每个单词的数量,只需将上面示例中的 set 替换为 Counter:
import string
from collections import Counter
words = Counter(word.lower().strip(string.punctuation) for word in words)
这会给你一个类似字典的对象,告诉你每个单词有多少。
您还可以从中获取唯一单词的数量(尽管如果您只关心它,它会更慢):
import string
from collections import Counter
words = Counter(word.lower().strip(string.punctuation) for word in words)
nword = len(words)
