【发布时间】:2020-03-09 13:09:02
【问题描述】:
我想遍历 2 个 CSV 文件,检查两个文件中的值何时匹配,并计算每个值匹配时出现的次数。输出应该是字典。
所以我有两个对齐的 CSV 文件。每个都有 2 列:“WORD”和“POS”(词性标签)。 Click to see example of file 1 Click to see example of file 2
在某些情况下,两个文件的每个单词都以相同的方式标记,但在许多其他情况下却没有。我想计算两个文件以相同方式标记的次数。
例如,如果 file1 有 WORD "human" 和 POS "PERS",而 file2 也有 WORD "human" 和 POS "PERS",我希望输出为:{PERS: 2} 这意味着 PERS 在两个文件中匹配了两次。我希望每个标签都这样: {TAG1:出现 n 次并同时匹配,TAG2:出现次数并同时匹配等 }
我只能弄清楚如何读取 一个 CSV 文件并使用此代码计算每个 POS 标签的使用次数:
import csv
from collections import defaultdict
def count_NER_tags(filename):
"""
Obtains the counts of each tag for the determined csv file
"""
dict_NER_counts = defaultdict(int)
with open(filename, "r") as csvfile:
read_csv = csv.reader(csvfile, delimiter="\t")
next(read_csv) #skip the header
for row in read_csv:
dict_NER_counts[row[2]] += 1
return dict_NER_counts
output:
{'O': 42123, 'ORG': 2092, 'LOC': 2094, 'MISC': 1268, 'PERS': 3145}
在读取两个 CSV 文件后,我不知道如何实现“if POS in file1 == POS in file2”,然后将它们的计数添加到字典中,如上面的代码所示。
【问题讨论】:
-
感谢您的评论。我刚刚编辑并添加了到目前为止的代码。
标签: python csv dictionary compare defaultdict