我有这个Python程序,它读取单词列表文件并检查使用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]):
最佳答案
您需要删除换行符:
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
然后从末尾开始切片,看看子字符串是否在字典中:
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 个四字符后缀,您只需要检查一次字典,则只能匹配一个 n
长度的子字符串一次,因此我们可以通过单个切片和查找一次性杀死 n
长度的子字符串。
关于python - 统计word文件中出现的后缀数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33108344/