如果存在长短划线(“ - ”),则返回完整字符串,如果为true,则返回第一个逗号(“,”)之前的所有内容。如何使用Python和Regex进行此操作?
from bs4 import BeautifulSoup
import requests
import json
import pandas as pd
request = requests.get('https://www.goodreads.com/quotes/tag/fun?page=1')
soup = BeautifulSoup(request.text, 'lxml')
# for loop
s = soup.find_all("div", class_="quoteText")[0].text
s = " ".join(s.split())
s[:s.index(",")]
s
原始输出:
“That does it," said Jace. "I\'m going to get you a dictionary for Christmas this year.""Why?" Isabelle said."So you can look up \'fun.\' I\'m not sure you know what it means.” ― Cassandra Clare, City of Ashes //<![CDATA[ function submitShelfLink(unique_id, book_id, shelf_id, shelf_name, submit_form, exclusive) { var checkbox_id = \'shelf_name_\' + unique_id + \'_\' + shelf_id; var element = document.getElementById(checkbox_id) var checked = element.checked if (checked && exclusive) { // can\'t uncheck a radio by clicking it! return } if(document.getElementById("savingMessage")){ Element.show(\'savingMessage\') } var element_id = \'shelfInDropdownName_\' + unique_id + \'_\' + shelf_id; Element.upda
期望的输出:
“That does it," said Jace. "I\'m going to get you a dictionary for Christmas this year.""Why?" Isabelle said."So you can look up \'fun.\' I\'m not sure you know what it means.” ― Cassandra Clare
答案 0 :(得分:1)
我不确定我是否理解它,但我认为你的意思是:
example_string = "part to return,example__text"
if example_string.count('__') > 0:
try:
result = re.search('(.*?)\,', example_string).group(0)
except:
result = None
print(result)
这会打印&#39;部分返回&#39;
如果你的意思是,&#39; __&#39;之间的字符串部分。和&#39;,&#39;我会用:
example_string = "lala__part to return, lala"
try:
result = re.search('__(.*?)\,', example_string).group(0)
except:
result = None
print(result)
答案 1 :(得分:1)
from bs4 import BeautifulSoup
from bs4.element import NavigableString
import requests
request = requests.get('https://www.goodreads.com/quotes/tag/fun?page=1')
soup = BeautifulSoup(request.text, 'html.parser')
# for loop
s = soup.find_all("div", class_="quoteText")[0]
text = ''
text += "".join([t.strip() for t in s.contents if type(t) == NavigableString])
for book_or_author_tag in s.find_all("a", class_ = "authorOrTitle"):
text += "\n" + book_or_author_tag.text.strip()
print(text)
你想要的引用是在初始的quoteText div中分割的,但是在它上面调用text
会返回你试图用正则表达式删除的所有CDATA垃圾。
通过循环遍历该div的每个子节点并检查它是否是可导航的字符串类型,我们只能提取您想要的实际文本数据。然后对作者和书进行处理,希望你的正则表达式变得简单得多。
答案 2 :(得分:1)
这是一个解决方案:
import re
s = 'adflakjd, fkljlkjdf ― Cassandra Clare, City of Ash, adflak'
x = re.findall('.*―.*?(?=,)', s)
print x
['adflakjd, fkljlkjdf ― Cassandra Clare']