【问题标题】:How to write multiple variables to a .txt file in python? [duplicate]如何在python中将多个变量写入.txt文件? [复制]
【发布时间】: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 topichow to ask。 “告诉我如何解决这个编码问题”不是堆栈溢出问题。我们希望您做出诚实的尝试,然后然后就您的算法或技术提出一个具体的问题。 Stack Overflow 并不打算取代现有的文档和教程。您需要完成有关 Python 文件的教程。

标签: python file write


【解决方案1】:

为了记录到一个文件,你要么有一个日志函数来写入一个文件,要么你有一个全局变量来指示文件,然后写入。您可以在 Python here 中了解有关文件的更多信息。

【讨论】:

  • 我知道如何写入文件,但我不知道如何将if条件以下的所有这些变量同时写入文件。
  • 将你的结果连接成一个字符串,然后记录下来。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-27
  • 1970-01-01
  • 2013-10-03
  • 2022-12-08
  • 2016-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多