我已经得到了这个python程序,它读取一个wordlist文件并检查后缀,这些后缀是使用endswith()方法在另一个文件中给出的。要检查的后缀保存到列表中: suffixList[]正在使用suffixCount[]进行计数。
以下是我的代码:
fd = open(filename, 'r')
print 'Suffixes: '
x = len(suffixList)
for line in fd:
for wordp in range(0,x):
if word.endswith(suffixList[wordp]):
suffixCount[wordp] = suffixCount[wordp]+1
for output in range(0,x):
print "%-6s %10i"%(prefixList[output], prefixCount[output])
fd.close()
产出如下:
Suffixes:
able 0
ible 0
ation 0
程序无法到达此循环:
if word.endswith(suffixList[wordp]):
发布于 2015-10-13 17:00:35
你需要去掉换行符:
word = ln.rstrip().lower()
这些单词来自一个文件,因此每一行都以换行符结尾。然后,您将尝试使用endswith
,它总是失败,因为您的后缀没有一个以换行符结尾。
我还将更改该函数以返回所需的值:
def store_roots(start, end):
with open("rootsPrefixesSuffixes.txt") as fs:
lst = [line.split()[0] for line in map(str.strip, fs)
if '#' not in line and line]
return lst, dict.fromkeys(lst[start:end], 0)
lst, sfx_dict = store_roots(22, 30) # List, SuffixList
然后从末尾切片,看看子字符串是否在dict中:
with open('longWordList.txt') as fd:
print('Suffixes: ')
mx, mn = max(sfx_dict, key=len), min(sfx_dict, key=len)
for ln in map(str.rstrip, fd):
suf = ln[-mx:]
for i in range(mx-1, mn-1, -1):
if suf in sfx_dict:
sfx_dict[suf] += 1
suf = suf[-i:]
for k,v in sfx_dict:
print("Suffix = {} Count = {}".format(k,v))
渐进式地分割字符串的结尾应该比检查每个字符串更快,特别是当您有许多相同长度的后缀时。它最多可以执行mx - mn
迭代,因此,如果您有20个4个字符后缀,您只需要检查一次dict,一次只能匹配一个n
长度子字符串,这样我们就可以使用单个切片和查找在同一时间杀死n
长度子字符串。
发布于 2015-10-13 17:19:32
您可以使用计数器来计数后缀的出现:
from collections import Counter
with open("rootsPrefixesSuffixes.txt") as fp:
List = [line.strip() for line in fp if line and '#' not in line]
suffixes = List[22:30] # ?
with open('longWordList.txt') as fp:
c = Counter(s for word in fp for s in suffixes if word.rstrip().lower().endswith(s))
print(c)
注意:如果您想忽略一行以上的单词,则添加.split()[0]
,否则这是不必要的。
https://stackoverflow.com/questions/33108344
复制相似问题