Python 中的关键字搜索并导出到 .txt 文件中的输出文档
Keyword Search and exporting to output doc in .txt file in Python
我正在尝试编写一个 python 函数来读取文本文件的每一行并搜索关键字:如果关键字在行中,我将尝试将该行导出到一个新的文本文档。这实际上会创建一种过滤文本行的方法。这是我目前所拥有的:
#trying to filter and print a line that contains a keyword in a csv or txt
file
import subprocess
import csv
def findandsearch(word):
textfile=open('textHCPC17_CONTR_ANWEB.txt', 'r+')
#openign the selected text file
outputfile=input('CMSOUTPUT.txt')
#classifying an ouput file
word=s'education' #designating a keyword
for line in textfile:
textfile.readline()
if word in textfile: #creating if clause
print('this is a match') #printing that this is match
outputfile.write(word) #I want to write the selected line of the text in the output file
textfile.close() #closing the original file
print(word) #I want to print the results
return #ending function
任何帮助将不胜感激,因为我没有 运行 语法错误,但我的输出文件是空白的。
您的 for 循环应如下所示:
for line in textfile:
if word in line:
print('blahblah')
outputfile.write(line)
textfile.close()
print(line)
return
在你的 if 子句中你比较了字符串和文件对象,甚至听起来很奇怪:-S
在 python 文档中对该解决方案进行了更好的解释:python doc - input and output
我正在尝试编写一个 python 函数来读取文本文件的每一行并搜索关键字:如果关键字在行中,我将尝试将该行导出到一个新的文本文档。这实际上会创建一种过滤文本行的方法。这是我目前所拥有的:
#trying to filter and print a line that contains a keyword in a csv or txt
file
import subprocess
import csv
def findandsearch(word):
textfile=open('textHCPC17_CONTR_ANWEB.txt', 'r+')
#openign the selected text file
outputfile=input('CMSOUTPUT.txt')
#classifying an ouput file
word=s'education' #designating a keyword
for line in textfile:
textfile.readline()
if word in textfile: #creating if clause
print('this is a match') #printing that this is match
outputfile.write(word) #I want to write the selected line of the text in the output file
textfile.close() #closing the original file
print(word) #I want to print the results
return #ending function
任何帮助将不胜感激,因为我没有 运行 语法错误,但我的输出文件是空白的。
您的 for 循环应如下所示:
for line in textfile:
if word in line:
print('blahblah')
outputfile.write(line)
textfile.close()
print(line)
return
在你的 if 子句中你比较了字符串和文件对象,甚至听起来很奇怪:-S
在 python 文档中对该解决方案进行了更好的解释:python doc - input and output