【问题标题】:How I can save the output in a text file如何将输出保存在文本文件中
【发布时间】:2021-04-24 21:45:46
【问题描述】:

我使用 TextRazor 库来分析文本并将其保存在文本文件中,但是当我打开文件时它是空的

import os 
textrazor.api_key = ""
client = textrazor.TextRazor(extractors=["word","entities", "topics","sentence","words"])
response = client.analyze("Twenty-four isolates (60%) were associated with pneumonia, 14 (35%) with upper respiratory tract infections, and 2 (5%) with bronchiolitis. Cough (82.5%), fever (75%), and malaise (58.8%) ")
for entity in response.entities():
    print(entity.id, entity.relevance_score, entity.confidence_score, entity.freebase_types)
cmd = os.popen('ls -w').read() # Récupération de la sortie de ls -a dans la variable cmd
print(cmd) # Affichage de la sortie
with open('monfichier.txt', 'w') as file:
        s=str(cmd)
        file.write(s)

【问题讨论】:

  • 我建议从您的问题中删除您的 API 密钥

标签: python output


【解决方案1】:

ls -w 不是有效命令,因为在 -w 之后需要一个整数。此外,不要使用os.popen:它不可移植。请改用 Python API(请参阅os.walk)。

【讨论】:

  • 我使用 os.walk 但我在文件中有这条消息:
  • 这是因为结果是一个 Python 生成器。您可以使用list(...) 转换为列表。请注意,os.walk 递归地遍历文件。如果你不想要这个,你可以改用os.scanfile。例如:list(e.name for e in os.scandir('.'))。如果你想要一个多行字符串作为结果,你可以使用'\n'.join(e.name for e in os.scandir('.'))
猜你喜欢
  • 2021-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多