【问题标题】:Can we import .txt file to python? [closed]我们可以将 .txt 文件导入 python 吗? [关闭]
【发布时间】:2018-11-29 12:57:47
【问题描述】:

我是python的新手。我有一个问题,我们如何将 .txt 文件导入 python? 我有一个 .txt 文件,里面有很多文本供我用 NLTK 分析。 你能告诉我如何开始分析文本吗? 提前谢谢你

【问题讨论】:

标签: python python-3.x nlp nltk natural-language-processing


【解决方案1】:

The Python Tutorial 是一本很棒的读物,涵盖了 Python 的核心用法。

举个例子,如果你有一个文本文件file.txt,每个句子单独一行,比如

This is a Larch.
Your father was a hamster and your mother smelled of elderberries.

然后你就可以在 Python 中加载这样的文件了

f_in = open('file.txt', 'r')
sentences = f_in.readlines()
f_in.close()  # make sure to close the file so other programs can use it

编辑:在您可以(并且应该)使用 Python 上下文管理器 with 的 cmets 中包含很好的建议。

上面的代码块等价于

with open('file.txt', 'r') as f_in:
    sentences = f_in.readlines()

您无需致电f_in.close()。这种类型的结构在 Python 中无处不在,非常值得习惯。

【讨论】:

    猜你喜欢
    • 2021-06-12
    • 1970-01-01
    • 2022-01-03
    • 2020-10-08
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    相关资源
    最近更新 更多