![](/img/trans.png)
[英]Finding all combinations of words of length 2 from list of words using python
[英]finding all unique words from a list using loops
我正在尝试根据从文本文件中提取的所有单词列表制作唯一单词列表。 我唯一的问题是用于迭代两个列表的算法。
def getUniqueWords(allWords):
uniqueWords = []
uniqueWords.append(allWords[0])
for i in range(len(allWords)):
for j in range(len(uniqueWords)):
if allWords[i] == uniqueWords[j]:
pass
else:
uniqueWords.append(allWords[i])
print uniqueWords[j]
print uniqueWords
return uniqueWords
如您所见,我创建了一个空列表并开始遍历两个列表。 此外,我附加了列表中的第一项,因为出于某种原因,它不会尝试尝试匹配我假设的单词,因为在空列表中,list[0] 不存在。 如果有人能帮我弄清楚如何正确地迭代这个,这样我就可以生成一个很棒的单词列表。
打印 uniqueWords[j] 只是为了调试,所以我可以看到在处理列表过程中出现了什么
我不是 python 专家,但认为这应该有效:
uniqueWords = []
for i in allWords:
if not i in uniqueWords:
uniqueWords.append(i);
return uniqueWords
编辑:
我测试过并且它有效,它只返回列表中的唯一单词:
def getUniqueWords(allWords) :
uniqueWords = []
for i in allWords:
if not i in uniqueWords:
uniqueWords.append(i)
return uniqueWords
print getUniqueWords(['a','b','c','a','b']);
['a', 'b', 'c']
我不喜欢(尝试)要求您选择糟糕算法的作业问题。 例如,更好的选择是使用set
或trie
。
您可以通过 2 个小的更改来修复您的程序
def getUniqueWords(allWords):
uniqueWords = []
uniqueWords.append(allWords[0])
for i in range(len(allWords)):
for j in range(len(uniqueWords)):
if allWords[i] == uniqueWords[j]:
break
else:
uniqueWords.append(allWords[i])
print uniqueWords[j]
print uniqueWords
return uniqueWords
首先,当您看到单词已经存在时,您需要停止循环
for j in range(len(uniqueWords)):
if allWords[i] == uniqueWords[j]:
break # break out of the loop since you found a match
第二种是使用for
/ else
构造而不是if
/ else
for j in range(len(uniqueWords)):
if allWords[i] == uniqueWords[j]:
break
else:
uniqueWords.append(allWords[i])
print uniqueWords[j]
也许你可以使用 collections.Counter 类? (特别是如果您还想计算每个单词在源文档中出现的次数)。
http://docs.python.org/2/library/collections.html?highlight=counter#collections.Counter
import collections.Counter
def getUniqueWords(allWords):
uniqueWords = Counter()
for word in allWords:
uniqueWords[word]+=1
return uniqueWords.keys()
另一方面,如果你只是想统计的话,就用一个集合:
def getUniqueWords(allWords):
uniqueWords =set()
for word in allWords:
uniqueWords.add(word)
return uniquewords #if you want to return them as a set
OR
return list(uniquewords) #if you want to return a list
如果您仅限于循环,并且输入相对较大,那么循环 + 二进制搜索是比仅循环更好的选择 - 类似这样:
def getUniqueWords(allWords):
uw = []
for word in allWords:
(lo,hi) = (0,len(uw)-1)
m = -1
while hi>=lo and m==-1:
mid = lo + (hi-lo)/2
if uw[mid]==word:
m = mid
elif uw[mid]<word:
lo = mid+1
else:
hi = mid-1
if m==-1:
m = lo
uw = uw[:m]+[word]+uw[m:]
return uw
如果您的输入有大约 100000 个单词,则使用此循环与简单循环的区别在于,您的 PC 在执行程序时不会发出噪音:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.