![](/img/trans.png)
[英]How to write a function that runs that function on 20 different csv files in Python?
[英]Python: Creating a function to write .CSV files
我想將多個語料庫的詞頻列表保存為 .CSV。 有沒有辦法讓 Python 根據變量名自動寫入文件名? (例如:corpus_a > corpus_a_typefrequency.csv)
我有以下代碼,它已經適用於個人語料庫:
from collections import Counter
import csv
counts = Counter(corpus_a)
counts = dict(sorted(counts.items(), key=lambda item: item[1],reverse=True))
with open('corpus_a_typefrequency.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
for key, value in counts.items():
writer.writerow([key, value])
PS:如果我只能計算單詞(沒有標點符號)並且不區分大小寫,那就太好了。 我還沒有想出如何在這里做到這一點。 我正在使用來自布朗語料庫的數據如下:
import nltk
from nltk.corpus import brown
corpus_a = brown.words()
我試過brown.words().lower().isalpha()
,但這不起作用。
你應該看看這個答案: https : //stackoverflow.com/a/40536047/5289234 。 它將允許您提取變量名稱並使用它來保存 csv。
import inspect
def retrieve_name(var):
"""
Gets the name of var. Does it from the out most frame inner-wards.
:param var: variable to get name from.
:return: string
"""
for fi in reversed(inspect.stack()):
names = [var_name for var_name, var_val in fi.frame.f_locals.items() if var_val is var]
if len(names) > 0:
return names[0]
from collections import Counter
import csv
counts = Counter(corpus_a)
counts = dict(sorted(counts.items(), key=lambda item: item[1],reverse=True))
with open(retrieve_name(corpus_a) +'_typefrequency.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
for key, value in counts.items():
writer.writerow([key, value])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.