【发布时间】:2017-03-05 19:10:25
【问题描述】:
我使用 python 从网页中抓取文本文件,如下所示。我抓取的数据包括我不需要的额外内容。我只需要加粗的部分。我还需要将每个粗体部分彼此分开。你能帮我这样做吗?在图像中,红色部分也是我试图从数据中提取的部分。
[
'\n249\nSRUS54 KFWD 051849\nRR5FWD\n:\n:
ALERT HOURLY ACCUMULATOR DATA\n:
NATIONAL WEATHER SERVICE FORT WORTH TX\n:
**1249 PM CST SUN MAR 5 2017**\n:\n:
HOURLY ACCUMULATOR INFORMATION TABLE\n:\n:
NOTE: ERRONEOU S REPORTS MAY BE RECEIVED UNDER CERTAIN\n:
WEATHER CONDITIONS\n:\n:
**********************************************************\n:
ID LOCATION ACCUMULATOR VALUE\n:
**********************************************************\n:
**CITY OF DALLAS ALERT SYSTEM**
\n**.A DCQT2 170305 C DH124216 /HGIRS
396.7**:
\n\n**.A DCVT2 170305 C DH123434 /HGIRS 516.8**:
\n\n**.A DAOT2 170305 C DH123721 /HGIRS 534.2**:\n\n**.A DDCT2
170305 C DH120338 /HGIRS 395.0**:\n\n**.A DAHT2 170305 C DH114758 /HGIRS
496.1**:\n\n\n\n']
This is an image of the data I grab from the web
import urllib
import re
htmlfile=urllib.urlopen("http://forecast.weather.gov/product.php?site=NWS&issuedby=FWD&product=RR5&format=CI&version=1&glossary=0")
htmltext=htmlfile.read()
regex='<pre class="glossaryProduct">(.+?)</pre>'
pattern=re.compile(regex,re.S)
out=re.findall(pattern, htmltext)
text=str(out)
saveFile=open('test.txt', 'w')
saveFile.write(text)
saveFile.close()
print (text)
【问题讨论】:
-
请提供您编写的代码。如果您提供格式良好的示例也会很好。
-
import urllib import re htmlfile=urllib.urlopen("forecast.weather.gov/…) htmltext=htmlfile.read() regex='
(.+?)
' pattern=re.compile(regex,re.S) out=re.findall(pattern, htmltext) text=str(out) saveFile=open('test.txt', 'w') saveFile.write(text) saveFile .close() 打印(文本) -
格式化列表输出。
-
我添加了我从网络上抓取的数据的图像,它有帮助吗?
-
尝试 BeautifulSoup 库来提取数据。它更有条理。此外,我在您提供的图像中没有看到任何粗体字。我认为您应该参考 SO 中的“如何提问”部分。