马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 blackantt 于 2023-4-18 23:03 编辑
<span style="font-size: 15px;">绵羊山姆睡不着觉。</span>
<span style="'outline: 0px;font-size: 14px;'">Sheep can't sleep</span>
if (sentence.name == 'span' and sentence.get('style') == 'font-size: 15px;') or (sentence.name == 'span' and sentence.get('style') == 'outline: 0px;font-size: 14px;'):
print(sentence.text)
if str(langid.classify(sentence.text)[0]) == 'en': #如果此句子是英文的,加入英文库
answer_en.append(sentence.text)
elif str(langid.classify(sentence.text)[0]) == 'zh': #如果此句子是中文的,加入中文库
answer_cn.append(sentence.text)
但对于 不规整的如下数据,以上结构就把 中英文句子合到1行上了。 还能怎么改一下,使之能解析不规整数据(英语入英库,中文入中库)?
<span style="font-size: 15px;">
"I'm six years old today," said Danny. "Will you come to my birthday party?"
<br style="outline: 0px;word-break: break-word;">
“我今天六岁了,”丹尼说。“你会来我的生日派对吗?”
<br style="outline: 0px;line-height: 22px;word-break: break-word;">
"I would be delighted." said the dinosaur.
<br style="outline: 0px;word-break: break-word;">“我很乐意去。”恐龙说。</span>
针对这种不规整的数据,可以通过正则表达式和BeautifulSoup库组合使用来解决问题。以下是一个示例代码:
import re
from bs4 import BeautifulSoup
import langid
# 示例HTML
html = '''
<span style="font-size: 15px;">
"I'm six years old today," said Danny. "Will you come to my birthday party?"
<br style="outline: 0px;word-break: break-word;">
“我今天六岁了,”丹尼说。“你会来我的生日派对吗?”
<br style="outline: 0px;line-height: 22px;word-break: break-word;">
"I would be delighted." said the dinosaur.
<br style="outline: 0px;word-break: break-word;">“我很乐意去。”恐龙说。</span>
'''
# 使用BeautifulSoup解析HTML
soup = BeautifulSoup(html, 'html.parser')
# 提取span标签中的文本内容
span_text = soup.find('span').text
# 使用正则表达式分割文本
sentences = re.split(r'[\n\xa0]', span_text)
# 中英文句子库
answer_en = []
answer_cn = []
# 对每个句子进行分类
for sentence in sentences:
if not sentence.strip():
continue
lang = langid.classify(sentence)[0]
if lang == 'en':
answer_en.append(sentence.strip())
elif lang == 'zh':
answer_cn.append(sentence.strip())
# 输出结果
print("English sentences:", answer_en)
print("Chinese sentences:", answer_cn)
这个示例代码可以解析提供的不规整数据,将英文句子添加到英文库,中文句子添加到中文库。这里使用了正则表达式分割span标签中的文本内容,然后使用langid库对每个句子进行语言分类。
|