Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用BS4从多个标记中提取数据后如何分割信息_Python_Beautifulsoup - Fatal编程技术网

Python 使用BS4从多个标记中提取数据后如何分割信息

Python 使用BS4从多个标记中提取数据后如何分割信息,python,beautifulsoup,Python,Beautifulsoup,我是Python新手。从文档中提取列表时出现问题。我的源文件不是真正的html,但它有一个标签来提取所需的数据 我使用此代码设法提取所需的数据 from bs4 import BeautifulSoup url = r"E:\Python\Sources\test.review" page = open(url) soup = BeautifulSoup(page.read()) for review in soup.find_all(['review_text','product_name'

我是Python新手。从文档中提取列表时出现问题。我的源文件不是真正的html,但它有一个标签来提取所需的数据

我使用此代码设法提取所需的数据

from bs4 import BeautifulSoup
url = r"E:\Python\Sources\test.review"
page = open(url)
soup = BeautifulSoup(page.read())
for review in soup.find_all(['review_text','product_name']):
    tokens=review.get_text()
    print tokens
然而,由于我不太熟悉在Python中使用list,因此存在如何破坏结果的问题。我尝试使用此代码,但它只返回第一个数据。我相信它,因为它引用了文件中的第一个数据。谢谢你的反馈

rvwTxt=soup.review_text.string
pName=soup.product_name.string
print rvwTxt
print pName

您可以在dict中分组,使用标记名进行分组,这样您就可以在一次过程中完成分组:

soup = BeautifulSoup(page.read(),"xml")
d = {"review_text":[], "product_name": []}
for review in soup.find_all(['review_text','product_name']):
    d[review.name].append(review.get_text())
或使用两个列表组件:

rev = [r.text for r in soup.find_all('product_name')]
prod = [p.text for p in soup.find_all('review_text')]
请回答您的问题,并将XML作为代码包含在内。