【问题标题】:How do I get Python to read and extract words from a text file? [duplicate]如何让 Python 从文本文件中读取和提取单词? [复制]
【发布时间】:2017-04-17 08:18:38
【问题描述】:

所以我需要编写一个打开一个txt文件的代码,然后将该文件的内容放入另一个txt文件中,问题是,我不知道如何从文件中提取信息的命令,我做了一些研究,发现这是最接近的东西,但这不是我需要的:How do I get python to read only every other line from a file that contains a poem

这是我目前的代码:

myFile = open("Input.txt","wt")
myFile.close()
myFile = open("Output.txt","wt")
myFile.close()

【问题讨论】:

标签: python


【解决方案1】:

简单试试这个

#open input file and read all lines and save it in a list
fin = open("Input.txt","r")
f = fin.readlines()
fin.close()

#open output file and write all lines in it
fout = open("Output.txt","wt")
for i in f:
    fout.write(i)
fout.close()

【讨论】:

  • 这个应该是这个非常基本的问题的答案,因为他想提取单词。它提供了一种结构,可以进一步用于例如正则表达式拆分" " 字符并处理每行中的单个单词。接受的答案也可以是shutil.copyfile("Input.txt", "Output.txt")
【解决方案2】:

将文本从一个文件复制到另一个文件的示例代码。也许它会帮助你:

inputFile = open("Input.txt","r")
text = inputFile.read()
inputFile.close()
outputFile = open("Output.txt","w")
outputFile.write(text)
outputFile.close()

【讨论】:

    猜你喜欢
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多