Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/72.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
基于HTML代码拆分Python字符串&8213;_Python_Html_Beautifulsoup - Fatal编程技术网

基于HTML代码拆分Python字符串&8213;

基于HTML代码拆分Python字符串&8213;,python,html,beautifulsoup,Python,Html,Beautifulsoup,我有一个程序,它可以和作者一起搜集引文。问题在于格式化输出。实际的引号只是html类的第一小部分,所以为了正确输出,我需要拆分字符串。下面是一个小的html片段: <div class="quoteText"> &ldquo;No matter how long you train someone to be brave, you never know if they are or not until something real happen

我有一个程序,它可以和作者一起搜集引文。问题在于格式化输出。实际的引号只是html类的第一小部分,所以为了正确输出,我需要拆分字符串。下面是一个小的html片段:

<div class="quoteText">
      &ldquo;No matter how long you train someone to be brave, you never know if they are or not until something real happens.&rdquo;
  <br>  &#8213; <--- want to split string here
  <span class="authorOrTitle">
    Veronica Roth,
  </span>
    <span id=quote_book_link_11735983>
      <a class="authorOrTitle" href="/work/quotes/15524542">Insurgent</a>
    </span>
目前,这将在html中稍后分割字符串,导致输出大量乱码


因此,基本上我需要帮助将特定的html转换为python可以识别的内容,或者只获取引用的替代方法。感谢您的帮助。

您的拆分不起作用,因为&8213;不是常规连字符,而是Unicode字符。BeautifulSoup将其从HTML实体转换为实际的Python Unicode字符,因此搜索字符串&8213;也不起作用

该字符的Unicode十六进制代码是2015,因此您可以使用

body = quote.find(class_="quoteText").get_text(strip=True).split('\u2015',1)[0]
然而,这是相当脆弱的。如果文档中有一个引号使用常规连字符而不是横条字符,该怎么办?那就不行了

如果您知道引号后面总是有换行符,\n您可以使用它来获得至少不完全依赖于特定的罕见Unicode字符的内容:

body = quote.find(class_="quoteText").text.lstrip().split("\n")[0]
但这也不是非常可靠,例如,如果你的报价中有一个换行符。您可以拆分BeautifulSoup将转换为的标记本身上的代码,但这让人感觉有点黑客味,而且还依赖于特定的格式

因为您知道这些都是引号,大概总是被引号包围,所以可以使用正则表达式匹配来获取引号内的所有文本。下面的代码检查常规引号以及卷曲的左双引号和右双引号:

import re

body = quote.find(class_="quoteText").text
quoteText = re.findall(r'(?:"|\u201c)(.*)(?:"|\u201d)', body)[0]

你打算通过解析这个html内容来提取什么信息?我只是想在没有任何额外html的情况下提取引用本身。
import re

body = quote.find(class_="quoteText").text
quoteText = re.findall(r'(?:"|\u201c)(.*)(?:"|\u201d)', body)[0]