python-3.x - 将字符串列表与另一个字符串列表进行比较
问题描述
positive_list = [line.strip() for line in open('positive-words.txt')] #converts text file to list
target_list = ['title', 'trump', 'impeached', 'for', 'abuse', 'of', 'power', 'two', 'weeks', 'before']
def wordcount(target_list, target_string):
counter = 0
for string in target_list:
if string == target_string:
counter += 1
else:
print('No matches found')
break
print('Number of matches: ' + counter)
wordcount(target_list, positive_list[x])
我能够使用字符串对象搜索 target_list,但无法遍历列表 positive_list 中包含的整个字符串。
有没有办法用positive_list循环target_list?
解决方案
您可以set
用于查找匹配项:
target_set = set(target_list)
pos_set = set(positive_list)
matches = pos_set.intersection(target_set)
wordcount = len(matches)
推荐阅读
- java - 试图将水平回收视图嵌套到垂直回收视图中
- ionic3 - 使用 google cordova 登录后,我被带到“www.google.com”
- c# - c#如何让web浏览器自动加载一个url
- scala - 为什么 DataFrame.stat.approxQuantile 因 n 个任务的序列化结果大小(1030.8 MB)大于 spark.driver.maxResultSize 而失败
- angular - 未找到传单标记生产环境角度 7
- javascript - 为每个单选按钮制作一个简单的真/假标志
- r - 粘贴向量的字符串索引
- swift - 在 TableView Cell 中设置 UIView 对象的宽度
- python - Python & Psycopg2 | 具有不同 WHERE 子句的动态查询
- html - 某些网页没有出现背景