我正在尝试用 Python 编写一个程序,为列表中的每个字符串搜索约 27,000 行。我要搜索的每个字符串都在一列中,并且在另一列中有一个“id”值,如果找到我想打印出来。我目前拥有的代码计算该字符串在文档中出现的次数,但我仍然无法找到一种方法来为找到字符串的每个唯一行返回特定值。
import csv
fin = open('data.csv')
words = ["happy","sad","good","bad","sunny","rainy"]
found = {}
count = 0
for line in fin:
for word in words:
if word in line:
count = count + 1
found[word] = count
print(found)
上面代码的主要语义问题是打印“found”字典只产生结果之一及其在“words”列表中的计数。
请您参考如下方法:
对于这样的事情,我认为使用 pandas 库可以让您保持理智。假设一个 15,000 行的 CSV 文件有两列,String 和 ID。
In [1]: import pandas as pd
In [2]: words = ['happy','sad','good','bad','sunny','rainy']
In [3]: df = pd.read_csv('data.csv')
In [4]: df.head(5)
Out[4]:
Strings ID
0 happy 1
1 sad 2
2 happy 3
3 sad 4
4 good 5
In [5]: for word in words:
...: print '{} : {}'.format(word, df['Strings'].str.lower().str.contains(word).sum())
...:
happy : 2501
sad : 2500
good : 2500
bad : 2500
sunny : 2499
rainy : 2500
或者,您可以只创建一个数据透视表,它会得到类似的结果。
In [30]: df_pt = df.pivot_table(index='Strings',values='ID',aggfunc=len)
In [31]: df_pt
Out[31]:
Strings
bad 2500
good 2500
happy 2501
rainy 2500
sad 2500
sunny 2499
Name: ID, dtype: int64
如果您需要获取每个单词的 ID,只需简单地选择/索引/过滤数据即可:
In [6]: df_happy = df[df['Strings'] == 'happy']
In [7]: df_happy.head(5)
Out[7]:
Strings ID
0 happy 1
2 happy 3
12 happy 13
14 happy 15
18 happy 19
如果你需要它作为一个列表,那么:
In [8]: list_happy = df_happy['ID'].tolist()
In [9]: list_happy[:5]
Out[9]: [1, 3, 13, 15, 19]
显然,我截断了一些部分,但思路保持不变。
