python3:从HTML(.txt)站点将文本行提取到Jupyter noteb上

2024-04-19 05:32:11 发布

您现在位置:Python中文网/ 问答频道 /正文

对Python来说是全新的,只有2天的时间。我正在尝试从HTML中提取特定的文本行到Jupyter笔记本,然后将其传输到Csv或xlsx。我采用了以下方法:

import requests
response = requests.get("https://www.ams.usda.gov/mnreports/wa_gr101.txt")
txt=response.text
print(txt) #This is essentially prints the entire txt file onto Jupyter

f=open("txt")
lines=f.readlines()
print (lines[28])

此时收到的错误消息是:

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-49-fc336b724c2c> in <module>()
----> 1 f=open("txt")
      2 lines=f.readlines()
      3 print (lines[28])

FileNotFoundError: [Errno 2] No such file or directory: 'txt'

我必须导入或嵌套在Jupyter笔记本文件或有一个更聪明的方法来做这件事?抱歉,如果这个问题听起来太新手。你知道吗

谢谢大家!你知道吗


Tags: 方法文本txtresponsehtml时间笔记本jupyter
1条回答
网友
1楼 · 发布于 2024-04-19 05:32:11

如果我理解正确,您只需要遍历返回的文件中的行。为此,您甚至不需要使用open函数,因为您的数据没有保存在文件中。它已经为您存储在一个变量中。您只需要将数据拆分成行,然后遍历它们。这样的方法应该有用:

import requests
response = requests.get("https://www.ams.usda.gov/mnreports/wa_gr101.txt")
txt=response.text
print(txt) #This is essentially prints the entire txt file onto Jupyter


# split the text wherever you find a newline
lines = txt.split('\n') 

# print line at index 28 (the 29th line)
print(lines[28]) 

# or iterate through the data
for line in lines:
    print(line)

PS:代码中的错误是由行f=open(“txt”)引起的。open函数用于读取文件,而不是变量。如果将变量txt中的数据保存到名为数据.txt然后你可以把它读作f=open(“数据.txt“”

相关问题 更多 >