【问题标题】:Removing string extra characters via python string functions通过python字符串函数删除字符串多余字符
【发布时间】:2016-09-30 09:39:39
【问题描述】:

这是我要从中提取位置信息的网络 CSS。

<div class="location">
    <div class="listing-location">Location</div>
    <div class="location-areas">
    <span class="location">Al Bayan</span>
    ‪,‪
    <span class="location">Nepal</span>
    </div>
    <div class="area-description"> 3.3 km from Mall of the Emirates </div>
    </div>

我使用的 Python Beautuifulsoup4 代码是:

   try:
            title= soup.find('span',{'id':'listing-title-wrap'})
            title_result= str(title.get_text().strip())
            print "Title: ",title_result
    except StandardError as e:
            title_result="Error was {0}".format(e)
            print title_result

输出:

"Al Bayanأ¢â‚¬آھ,أ¢â‚¬آھ

                            Nepal"

如何将格式转换为以下格式

['Al Bayan', 'Nepal']

获取此输出的代码的第二行应该是什么

【问题讨论】:

  • 产生此输出的 HTML 是什么?
  • 都是那种格式的吗?一些 jbberish,然后是 2 个换行符,然后是真正的文本?
  • 试试这个解决方案stackoverflow.com/a/2743163/524743
  • @LutzHorn 它是一个美丽的soup4(python)
  • 发布更多代码实际上可能会有所帮助。

标签: python string python-2.7 python-3.x beautifulsoup


【解决方案1】:

你读错了,只是读取带有类位置的跨度

soup = BeautifulSoup(html, "html.parser")
locList = [loc.text for loc in soup.find_all("span", {"class" : "location"})]
print(locList)

这会打印出您想要的内容:

['Al Bayan', 'Nepal']

【讨论】:

  • [u'Al Bayan', 'u'Nepal] 这是输出。
  • 带字符串的映射。这将给出您预期的结果。 map(str,output_list)
  • @Panetta 我稍微改变了它,现在运行它。当已经有一个列表组合时,没有理由使用地图
  • @Keatinge 你是对的。我只是建议了一个替代方案。
  • @Panetta:不要在 Unicode 字符串上调用 str()——只要你在其中得到一个非 ascii 字符,它就会中断。如果您不喜欢,请手动格式化列表:[u'Al Bayan', 'u'Nepal] 文本表示,例如,print("\n".join(locList))(将每个项目打印在自己的行上)。见Python string prints as [u'String']
【解决方案2】:

有一个单一的解决方案。将a 视为您的字符串。

In [38]: [i.replace("  ","") for i in filter(None,(a.decode('unicode_escape').encode('ascii','ignore')).split('\n'))]
Out[38]: ['Al Bayan,', 'Nepal']

【讨论】:

  • asci 编解码器无法编码字符 u'\u202a'。试过了,这是错误
  • @Panetta 您的确切错误是什么。以及您作为输入提供的内容。它对我有用。
【解决方案3】:

您可以使用正则表达式仅过滤字母和空格:

>>> import re
>>> re.findall('[A-Za-z ]+', area_result)
['Al Bayan', ' Nepal']

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    • 2018-11-10
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多