Python 如何重组词语
运行此代码时,输出的一些单词被拆分。就像“公差”这个词一样,它也被分为公差。我查看了html源代码,似乎页面就是这样创建的 还有许多其他的地方,这个词是分开的。在写成文本之前,我如何重新组合它们Python 如何重组词语,python,beautifulsoup,Python,Beautifulsoup,运行此代码时,输出的一些单词被拆分。就像“公差”这个词一样,它也被分为公差。我查看了html源代码,似乎页面就是这样创建的 还有许多其他的地方,这个词是分开的。在写成文本之前,我如何重新组合它们 import requests, codecs from bs4 import BeautifulSoup from bs4.element import Comment path='C:\\Users\\jason\\Google Drive\\python\\' def tag_visible(
import requests, codecs
from bs4 import BeautifulSoup
from bs4.element import Comment
path='C:\\Users\\jason\\Google Drive\\python\\'
def tag_visible(element):
if element.parent.name in ['sup']:
return False
if isinstance(element, Comment):
return False
return True
ticker = 'TSLA'
quarter = '18Q2'
mark1= 'ITEM 1A'
mark2= 'UNREGISTERED SALES'
url_new='https://www.sec.gov/Archives/edgar/data/1318605/000156459018019254/tsla-10q_20180630.htm'
def get_text(url,mark1,mark2):
html = requests.get(url)
soup = BeautifulSoup(html.text, 'html.parser')
for hr in soup.select('hr'):
hr.find_previous('p').extract()
texts = soup.findAll(text=True)
visible_texts = filter(tag_visible, texts)
text=u" ".join(t.strip() for t in visible_texts)
return text[text.find(mark1): text.find(mark2)]
text = get_text(url_new,mark1,mark2)
file=codecs.open(path + "test.txt", 'w', encoding='utf8')
file.write (text)
file.close()
这个页面标记非常糟糕。您需要删除多余的标签来解决问题。幸运的是,美孚集团能承担起这项重任。下面的代码将删除所有字体标记
这个页面标记非常糟糕。您需要删除多余的标签来解决问题。幸运的是,美孚集团能承担起这项重任。下面的代码将删除所有字体标记 您正在处理用Microsoft Word格式化的HTML。不要提取文本并尝试在没有上下文的情况下处理它 您想要处理的部分被清楚地描述出来,这对您的案例最有帮助,因为文本几乎被标签任意分割 现在,干净地提取文本突然变得微不足道:
for elem in sec_section(soup, 'ITEM_1A_RISK_FACTORS'):
clean_word(elem)
if not isinstance(elem, str):
elem = elem.get_text(strip=True)
print(elem)
这将在文本的其余部分中输出:
•that the equipment and processes which we have selected for Model 3 production will be able to accurately manufacture high volumes of Model 3 vehicles within specified design tolerances and with high quality;
文本现在已正确连接,不再需要重新组合
整个部分仍在一张表中,但clean_word现在将其清理到更合理的程度:
•
我们为3型生产选择的设备和工艺将能够在规定的设计公差范围内以高质量准确制造大量3型车辆
因此,您可以使用更智能的文本提取技术,以进一步确保在这里进行干净的文本转换;您可以将这些项目符号表转换为*前缀,例如:
def convert_word_bullets(soup, text_bullet="*"):
for table in soup.select('div[align=left] > table'):
div = table.parent
bullet = div.find(string='\u2022')
if bullet is None:
# not a bullet table, skip
continue
text_cell = bullet.find_next('td')
div.clear()
div.append(text_bullet + ' ')
for i, elem in enumerate(text_cell.contents[:]):
if i == 0 and elem == '\n':
continue # no need to include the first linebreak
div.append(elem.extract())
此外,如果您运行,您可能也希望跳过分页符,这是[页码]和元素的组合
for pagebrk in soup.select('p ~ hr[style^=page-break-after]'):
pagebrk.find_previous_sibling('p').decompose()
pagebrk.decompose()
这比您自己的版本更明确,在您自己的版本中,您将删除所有元素和前面的元素,而不管它们实际上是否是同级元素
在清理Word HTML之前执行这两个命令。与您的功能相结合,共同成为:
def get_text(url, item_name):
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
for pagebrk in soup.select('p ~ hr[style^=page-break-after]'):
pagebrk.find_previous_sibling('p').decompose()
pagebrk.decompose()
convert_word_bullets(soup)
cleaned_section = map(clean_word, sec_section(soup, item_name))
return ''.join([
elem.get_text(strip=True) if elem.name else elem
for elem in cleaned_section])
text = get_text(url, 'ITEM_1A_RISK_FACTORS')
with open(os.path.join(path, 'test.txt'), 'w', encoding='utf8') as f:
f.write(text)
您正在处理用Microsoft Word格式化的HTML。不要提取文本并尝试在没有上下文的情况下处理它
您想要处理的部分被清楚地描述出来,这对您的案例最有帮助,因为文本几乎被标签任意分割
现在,干净地提取文本突然变得微不足道:
for elem in sec_section(soup, 'ITEM_1A_RISK_FACTORS'):
clean_word(elem)
if not isinstance(elem, str):
elem = elem.get_text(strip=True)
print(elem)
这将在文本的其余部分中输出:
•that the equipment and processes which we have selected for Model 3 production will be able to accurately manufacture high volumes of Model 3 vehicles within specified design tolerances and with high quality;
文本现在已正确连接,不再需要重新组合
整个部分仍在一张表中,但clean_word现在将其清理到更合理的程度:
•
我们为3型生产选择的设备和工艺将能够在规定的设计公差范围内以高质量准确制造大量3型车辆
因此,您可以使用更智能的文本提取技术,以进一步确保在这里进行干净的文本转换;您可以将这些项目符号表转换为*前缀,例如:
def convert_word_bullets(soup, text_bullet="*"):
for table in soup.select('div[align=left] > table'):
div = table.parent
bullet = div.find(string='\u2022')
if bullet is None:
# not a bullet table, skip
continue
text_cell = bullet.find_next('td')
div.clear()
div.append(text_bullet + ' ')
for i, elem in enumerate(text_cell.contents[:]):
if i == 0 and elem == '\n':
continue # no need to include the first linebreak
div.append(elem.extract())
此外,如果您运行,您可能也希望跳过分页符,这是[页码]和元素的组合
for pagebrk in soup.select('p ~ hr[style^=page-break-after]'):
pagebrk.find_previous_sibling('p').decompose()
pagebrk.decompose()
这比您自己的版本更明确,在您自己的版本中,您将删除所有元素和前面的元素,而不管它们实际上是否是同级元素
在清理Word HTML之前执行这两个命令。与您的功能相结合,共同成为:
def get_text(url, item_name):
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
for pagebrk in soup.select('p ~ hr[style^=page-break-after]'):
pagebrk.find_previous_sibling('p').decompose()
pagebrk.decompose()
convert_word_bullets(soup)
cleaned_section = map(clean_word, sec_section(soup, item_name))
return ''.join([
elem.get_text(strip=True) if elem.name else elem
for elem in cleaned_section])
text = get_text(url, 'ITEM_1A_RISK_FACTORS')
with open(os.path.join(path, 'test.txt'), 'w', encoding='utf8') as f:
f.write(text)
看起来您正在将文本与此处的空格连接在一起:text=u.joint.strip for t in visible_textsDon't use codecs.open。在Python3上使用open,在Python2上使用io.open。当涉及到文件I/O时,编解码器代码库存在许多性能和实现问题。看起来您正在将文本与空格连接在一起:text=u.joint.strip for t in visible_textsDon't use codecs.open。在Python3上使用open,在Python2上使用io.open。当涉及到文件I/O时,编解码器代码库有很多性能和实现问题。