使用 python 从文本文件中获取不同的单词
get distinct word from textfile using python
我有一个关于从包含大约 14000 个句子的文本文件中获取不同单词的问题。现在我试图从这个文本文件中取出每一个不同的词,所以我不再有任何双打所以它会使列表更短,以便以后的过程,例如散列(否则我会有相同的散列倍数次)。
我已经使用 python 研究了多个选项,但我发现的唯一想法是 python 中的一个独特的单词计数器。
有什么办法可以做到吗?
在提出您自己的问题之前,请尝试查看文档和其他堆栈溢出问题。如果它是像这样通用的东西(即不添加重复项),则很有可能之前已经有人问过它。
#Psudocode
my_set = {'words go here'}
for each line in file:
for each word in line:
my_set.add(word) #Word will only be added if it is not already present, a property of the set class
我认为你的问题已经暗示了一个好的解决方案:
"a textfile with about 14000 sentences"
with open('file.txt') as f:
data = f.readlines() # assuming each line is a sentence or the like
"get every distinct word" 和 "distinct word counter" 和 "hashing (otherwise i'd have the same hash multiple times)"
— 取决于它的使用方式,如前所述,set
会为您完成此操作。您提到了散列,集合使用散列将对象定位到存储桶中。
unique_words = set()
for line in data:
clean_line = line.rstrip()
words = clean_line.split() # get all the words from one line
unique_words.update(words) # throws these words into the set
剧组会为你处理副本
您可以使用 python 中的设置功能。一个集合不允许添加重复项。查看下面的代码。
word_set = set()
for line in open("test.txt",'r'):
for word in line.split():
word_set.add(word)
print(word_set)
文件 test.txt 包含:
Hello World and again Hello World
输出:
{'Hello', 'again', 'World', 'and'}
我有一个关于从包含大约 14000 个句子的文本文件中获取不同单词的问题。现在我试图从这个文本文件中取出每一个不同的词,所以我不再有任何双打所以它会使列表更短,以便以后的过程,例如散列(否则我会有相同的散列倍数次)。
我已经使用 python 研究了多个选项,但我发现的唯一想法是 python 中的一个独特的单词计数器。
有什么办法可以做到吗?
在提出您自己的问题之前,请尝试查看文档和其他堆栈溢出问题。如果它是像这样通用的东西(即不添加重复项),则很有可能之前已经有人问过它。
#Psudocode
my_set = {'words go here'}
for each line in file:
for each word in line:
my_set.add(word) #Word will only be added if it is not already present, a property of the set class
我认为你的问题已经暗示了一个好的解决方案:
"a textfile with about 14000 sentences"
with open('file.txt') as f:
data = f.readlines() # assuming each line is a sentence or the like
"get every distinct word" 和 "distinct word counter" 和 "hashing (otherwise i'd have the same hash multiple times)"
— 取决于它的使用方式,如前所述,set
会为您完成此操作。您提到了散列,集合使用散列将对象定位到存储桶中。
unique_words = set()
for line in data:
clean_line = line.rstrip()
words = clean_line.split() # get all the words from one line
unique_words.update(words) # throws these words into the set
剧组会为你处理副本
您可以使用 python 中的设置功能。一个集合不允许添加重复项。查看下面的代码。
word_set = set()
for line in open("test.txt",'r'):
for word in line.split():
word_set.add(word)
print(word_set)
文件 test.txt 包含:
Hello World and again Hello World
输出:
{'Hello', 'again', 'World', 'and'}