我最近從
我的問題是我試圖在 Python 中計算 Posts.csv 檔案中僅感興趣的特定標簽的頻率,給定一個串列。例如,假設我在 Python 中有以下串列:
tagsOfInterest = ['version-control', 'git', 'git-merge', 'bash', 'microservices']
Only in the Tags column of the CSV file, I would like to count how many times the tag version-control appears, how many times the tag git appears, how many times the tag git-merge appears, etc...
I've been struggling to do this because you'll notice that each row in the Tags column is formatted as a continuous string, with each different tag word only separated by a <>. For instance, in the first row, a post has been tagged with <version-control><projects-and-solutions><monorepo>.
My original attempt involved first reading the Posts.csv file, and then adding each row in the Tags column to a list, as such:
from pandas import *
import csv
# Read data
data = read_csv("Posts.csv")
# Add each row in the "Tags" column to a list:
tags_col = data['Tags'].tolist()
and then my idea was to just tokenize each tag word. However, the Posts.csv file is so large, that my computer runs out of memory just from creating the list!
因此,我的問題是:給定一個感興趣的標簽串列,例如,tagsOfInterest = ['version-control', 'git', 'git-merge', 'bash', 'microservices']我如何從檔案的Tags列中計算該串列中每個元素的頻率Posts.CSV?
uj5u.com熱心網友回復:
import csv
from collections import Counter
counts = Counter()
for row in csv.reader(open('Posts.csv')):
for tag in row[1].lstrip('<').rstrip('>').split('><'):
counts[tag] = 1
print(counts)
如果需要,您可以使用 DictReader 來row['Tags']代替row[1].
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/439262.html
標籤:Python 列表 CSV 频率 stackexchange-api
