如何解决收集计数器-如何消除对单词中的字符“”进行计数
我写了一个脚本来查找文件/词典中最长的单词。 但是在英语中使用撇号“'”,我想跳过它。
from collections import Counter
import time
words = open('english').read().splitlines()
time_before = time.time()
k = Counter(words)
longest = max(k,key=len)
print('The longest word in Dictionary is:',longest,'has',len(longest),'characters')
time_after = time.time()
time_taken = time_after - time_before
print ( 'Longest word found in: ',time_taken)
print(".......................")
解决方法
替换用于max()
的密钥:
longest = max(k,key=lambda s:len(letter for letter in s if letter != "'"))
您当然可以自定义此解决方案,以排除更多字母,或仅包含特定内容,等等。
,要在单词长度计数中排除撇号及其后的所有字符:
max(k,key=lambda word: len(word.split("'")[0]))
,
因此,对于初学者来说,这里没有理由使用Counter
,实际上您并没有计算任何数字(除非出于某种原因您的词典文件中有重复的单词)
您应该能够通过过滤来检查单词是否包含撇号:
import time
with open('english') as f:
words = f.read().splitlines()
time_before = time.time()
filtered = (word for word in words if "'" not in word)
longest = max(filtered,key=len)
print('The longest word in Dictionary is:',longest,'has',len(longest),'characters')
time_after = time.time()
time_taken = time_after - time_before
print ( 'Longest word found in: ',time_taken)
print(".......................")
,
嗨,您可以只用单引号代替,然后开始计数。
txt = "hi it's me"
x = txt.replace("'","")
print(x)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。