![](/img/trans.png)
[英]Redirect output from print function to Text and and disable it
[英]Saving output from defined for loop function - redirect print output not working
我已經預處理了 csv 文件中的一些文本,這些文本由用於任務的不同技術標記,並為每種技術創建了一個新的干凈文本列。 我想按降序查找每種技術的描述(即純文本)的詞頻(它們已經被分組)並執行以下操作:
from collections import Counter
df['Count'] = df['clean_text'].str.lower().split().apply(Counter)
count = df['Count']
def most_common():
for i in count:
x = Counter(i)
print(x.most_common())
當我調用 most_common() 時,我成功地按降序獲得了每種技術的詞頻作為輸出,但我想將此輸出保存到文件或使用輸出在我的數據框中創建一個新列。 我已經研究過使用 open 命令等重定向打印輸出並將其保存到 python,但它沒有顯示所有輸出,它只顯示第一個。 任何人都可以幫助保存此函數的輸出,以便將其添加到數據框或另存為自己的 csv 嗎?
作為參考,這是我之前嘗試過的一段代碼:
for i in count:
with open("randomfile.txt", "w") as external_file:
x = Counter(i)
print(x.most_common(), file=external_file)
external_file.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.