【发布时间】:2021-05-21 21:34:10
【问题描述】:
我有一个程序可以计算文本文件每个句子中单词的频率及其 PoS 标签。句子之间用标签SPACE分隔,可以查看here。
我不想打印每个输出(打印所有内容需要很长时间),而是想将输出写入文件,但我不知道该怎么做,因为有多个带整数的变量要写入文件(sentence_num,Count[key])。有没有办法有效地完成这些任务?我的代码如下:
import re
import os
import sys
from pathlib import Path
while True:
try:
file_to_open =Path(input("Please, insert your file path: "))
with open(file_to_open,'r', encoding="utf-8") as f:
sentences = f.read()
break
except FileNotFoundError:
print("\nFile not found. Better try again")
except IsADirectoryError:
print("\nIncorrect Directory path.Try again")
units=sentences.split('SPACE')
print(len(units))
count={}
for sentence_num, unit in enumerate(units, 1):
lines=unit.split('\n')
for s in lines:
if s in count:
count[s]+=1
else:
count[s]=1
for key in count:
if 'VERB' in key and count[key] >1:
print(sentence_num,key, count[key]
elif 'NOUN' in key and count[key] >1:
print(sentence_num,key, count[key]
elif 'ADJ' in key and count[key] >1:
print(sentence_num,key, count[key]
elif 'ADV' in key and count[key] >1:
print(sentence_num,key, count[key]
【问题讨论】:
-
请从intro tour 重复on topic 和how to ask。 “告诉我如何解决这个编码问题”不是堆栈溢出问题。我们希望您做出诚实的尝试,然后然后就您的算法或技术提出一个具体的问题。 Stack Overflow 并不打算取代现有的文档和教程。您需要完成有关 Python 文件的教程。