如何从文本文件中仅提取具有特定单词的行并编写新的行?



如何从请求(在线文本文件)中提取只有特定单词的行并写入新的文本文件?我被困在这里了…

这是我的代码:

r = requests.get('http://website.com/file.txt'.format(x))
with open('data.txt', 'a') as f:
if 'word' in line:
f.write('n')
f.writelines(str(r.text))
f.write('n')

如果我删除:if 'word' in line:,它工作,但对所有行。所以它只是将所有行从一个文件复制到另一个文件。

是否知道如何给出正确的命令来提取(过滤)仅具有特定单词的行?

  • 更新:这是工作的,但如果这个词存在于请求文件中,它开始复制所有行,我只需要复制与'SOME word '的行。
  • 我已经添加了这个代码:

    for line in r.t text.split('n'):

*谢谢大家的回答,如果我没有说清楚,我很抱歉。

也许这会有帮助。

无论何时调用POST/GET或其他方法,都要检查HTTP响应代码。

现在让我们假设响应文本中的行是用换行符('n')分隔的,并且您想要写一个新文件(如果想要追加,请将模式更改为'a')。然后:

import requests
(r := requests.get('SOME URL')).raise_for_status()
with open('SOME FILENAME', 'w') as outfile:
for line in r.text.split('n'):
if 'SOME WORD' in line:
print(line, file=outfile)
break

注意:

您需要Python 3.8+才能利用这段代码中的walrus操作符

我建议您采取以下步骤来正确处理该文件:

Step1:Streamline the download file to a temporary file
Step2:Read lines from the temporary file
Step3:Generate main file based on your filter
Step4:Delete the temporary file
下面的代码执行以下步骤:
import requests
import os
def read_lines(file_name):
with open(file_name,'r') as fp:
for line in fp:
yield line

if __name__=="__main__":
word='ipsum'
temp_file='temp_file.txt'
main_file='main_file.txt'
url = 'https://filesamples.com/samples/document/txt/sample3.txt'
with open (temp_file,'wb') as out_file:
content = requests.get(url, stream=True).content
out_file.write(content)

with open(main_file,'w') as mf:
out=filter(lambda x: word in x,read_lines(temp_file))
for i in out:
mf.write(i)
os.remove(temp_file)

好吧,为了检查if语句,您必须添加缺少的行。

import requests
r = requests.get('http://website.com/file.txt').text
with open('data.txt', 'a') as f:
for line in r.splitlines(): #this is your loop where you get a hold of line.
if 'word' in line: #so that you can check your 'word'
f.write(line) # write your line  contains your word

最新更新