我有一个使用汤findAll创建的数组,其第一个元素具有以下信息。在此列表中,我只需要地址信息,即
“ 54000 NANCY 47 RUE SERGENT BLANDAN”,如何获得此信息?
git rebase -i
答案 0 :(得分:1)
您可以取出您的琴弦,并在取出感兴趣的物品后使用re进行一些琴弦清洁。这是特定于您的json
import re
s = {
"div": {
"@class": "result-left",
"h3": "Establishment(s)",
"div": [
{
"label": "Status:",
"#text": "Closed"
},
{
"p": {
"label": "Brand name:",
"#text": "LE ZODIAC"
}
},
{
"p": {
"label": "Usual name:"
}
},
{
"p": {
"label": "Address:",
"br": [
"",
"54000\r\n\t\t\t\t\t\t\t\t\t\t\tNANCY"
],
"#text": "47\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tRUE\r\n\t\t\t\t\t\t\t\t\t\tSERGENT BLANDAN"
}
},
{
"p": {
"label": "Principal activity:",
"#text": "47.78C - \r\n\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\tAutres commerces de détail spécialisés divers"
}
},
{
"p": {
"label": {
"sup": "*",
"#text": [
"Employee numbers",
":"
]
}
}
},
{
"p": {
"label": "Year employee numbers verified:"
}
}
]
}
}
result = re.sub(r'\r\n\t+',' ',' '.join([s['div']['div'][3]['p']['br'][1], s['div']['div'][3]['p']['#text']]))
print(result)
答案 1 :(得分:0)
具有很多重复的制表符,CRLF和其他空格似乎不太方便。 定义该功能值得您花时间:
def simplify_ws(s: str):
"""Coalesces multiple whitespace, e.g. 'a b c' --> 'a b c'."""
return ' '.join(s.split())
您的字典非常好而且很完整, 因此它肯定可以用于解决方案。 但是让bs4迭代 just 您最喜欢的段落会更方便:
for p in soup.find_all('p'):
txt = p.get_text()
if 'Address:' in txt:
print(simplify_ws(txt))
您可能希望在此之上进行更多过滤和调整。