[英]Multiple Search Terms in List
我正在计算eth
或btc
是否出现在listy
中
searchterms = ['btc', 'eth']
listy = ['Hello, my name is btc', 'hello, my name is ETH,', 'i love eth', '#eth is great', 'barbaric tsar', 'nothing']
cnt = round((sum(len(re.findall('eth', x.lower())) for x in listy)/(len(listy)))*100)
print(f'{cnt}%')
该解决方案仅查找eth
。 如何查找多个搜索词?
底线:我在searchterms
中有一个搜索词列表。 我想看看其中是否有任何出现在listy
中。 从那里,我可以执行列表中出现的这些术语的百分比。
我想说的是,不要使问题复杂化并使用 re,而是使用简单的经典列表理解。
listy = ['Hello, my name is btc', 'hello, my name is ETH,', 'i love eth', '#eth is great', 'barbaric tsar', 'nothing']
print(len([i for i in listy if 'btc' in i.lower() or 'eth' in i.lower()]) * 100 / len(listy))
它提高了代码的可读性和简单性。
让我知道它是否有帮助!
您需要使用 pipe “|” 在要搜索的值之间。 在您的代码re.findall('eth', x.lower()
更改为re.findall(r"(eth)|(btc)", x.lower()
listy = ['Hello, my name is btc', 'hello, my name is ETH,', 'i love eth', '#eth is great', 'barbaric tsar', 'nothing']
cnt = round((sum(len(re.findall(r"(eth)|(btc)", x.lower())) for x in listy)/(len(listy)))*100)
print(f'{cnt}%')
67%
更多的代码提供了良好的可读性。 还添加要搜索的其他单词,只需将它们添加到列表search_for
。 计算它使用默认字典。
listy = ['Hello, my name is btc', 'hello, my name is ETH,', 'i love eth', '#eth is great', 'barbaric tsar', 'nothing']
my_dict = defaultdict(int)
search_for = ['btc', 'eth']
for word in listy:
for sub in search_for:
if sub in word:
my_dict[sub] += 1
print(my_dict.items())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.