python - 检查字符串列表以提取某些单词的有效方法
问题描述
我正在尝试检查 20,000 个字符串列表并与某些单词/短语进行比较,以将它们正确分类为 3 类。
这是字符串的示例列表:
sample = ["the empty bus behind me", "the facility is close", "my order was canceled", "no empty on site", "no bus for me to move"]
所以我想检查一个字符串是否有:
"empty" and "bus" and "empty" then emptyCount += 1
"order canceled" or "canceled" then cancelcount += 1
"empty" or "site" or "no empty on site" then site += 1
我有一个代码可以做到这一点,但我不认为它更有效,而且实际上可能会遗漏一些关键点。关于如何去做有什么建议吗?
site = 0
cancel = 0
empty = 0
count = 0
for i in sample:
if "empty" and "bus" and "empty" in i:
emptycount += 1
elif "order canceled" or "canceled":
cancelcount += 1
elif "empty" or "site" or "no empty on site"
site += 1
else:
count += 1
解决方案
你甚至不需要提取。
您需要做的就是搜索并增加计数
sample = ["the empty bus behind me", "the facility is close", "my order was canceled", "no empty on site", "no bus for me to move"]
empty_counter = 0
for string_item in sample:
if 'empty' in string_item:
empty_counter += 1
print(empty_counter)
如果您正在寻找效率,那么我建议使用熊猫。这将使您的效率提高 100 倍,具体取决于数据的大小,它是一个数据科学包,这意味着它可以非常快速地处理数百万个数据。
#import pandas package.
import pandas as pd
sample = ["the empty bus behind me", "the facility is close", "my order was canceled", "no empty on site", "no bus for me to move"]
# create a pandas series
sr = pd.Series(sample)
#search for match and store results
results = sr.str.match(pat = '(empty)&(bus)' )
#gives total number of matching items
print(results.shape[0])
推荐阅读
- javascript - 用 ul 隐藏 div,其中 li 带有特定文本
- join - 在 sequelize 中加入表
- javascript - 数据表预提交 2 个文件
- ajax - 使用 ajax 进行动态 ViewComponent 更新
- mysql - mysql 5.7.23 几个小时后变慢,需要重启
- visual-studio-2010 - 基本 Win32 C 编程
- reactjs - 如何在 React 渲染前设置 props
- javascript - tensorflow.js 有没有办法输入带有-1 作为形状值之一的形状
- sql-server - 导入元素名称中带有连字符的 XML 文件时出现问题
- mongodb-3.6 - 如何在 mongoDB v3.6.5 中使用聚合时将字符串转换为双精度