Skip to main content
 首页 » 编程设计

python之在一行文本文件中查找多个唯一单词

2025年05月04日9jiqing9006

我想创建一个 Python 程序来查找文本文件中一行中的唯一单词。

文本文件“details”有以下几行

My name is crazyguy 
i am studying in a college and i travel by car 
my brother brings me food for eating and we will go for shopping after food. 

它必须返回输出为

4 
10 #(since i is repeated) 
13 #(Since food and for are repeated) 

如果代码有效,它在挖掘数据时是否会以同样的方式处理更大的文本文件?

请您参考如下方法:

您可以使用 set 遍历所有行拆分来创建列表并使其设置为查找唯一值并查找其计数

with open("filename","r") as inp: 
     for line in inp: 
         print len(set(line.split()))