
本教程详细介绍了如何将半结构化的纯文本文件(如factiva文章)高效地解析并转换为结构化的pandas dataframe。文章涵盖了两种主要方法:一种是基于固定行号的简单提取方案,适用于格式严格一致的文本;另一种是利用正则表达式实现更灵活、更精确的数据抽取,能够捕获文章标题、字数、日期、来源、语言及正文内容。教程还演示了如何批量处理多个文件,并讨论了数据清洗与错误处理的关键考量,旨在帮助用户将原始文本数据转化为可分析的格式。
在数据分析和处理领域,我们经常会遇到需要从非结构化或半结构化文本中提取特定信息并将其整理成结构化数据的场景。例如,从新闻稿、报告或文档中自动提取文章标题、发布日期、作者、内容等,以便后续进行统计分析或机器学习任务。本教程将以Factiva文本文件为例,详细讲解如何使用Python和Pandas库实现这一目标。
首先,我们需要仔细分析待处理的文本文件的结构。Factiva文件通常包含一系列元数据(如字数、日期、来源、语言)和文章正文。以提供的样本为例:
Section US Treas Dept on Feb 13 makes public text of speech made by Sec Shultz at... 228 words 15 February 1974 New York Times Abstracts NYTA Pg. 1, Col. 1 English c. 1974 New York Times Company US Treas Dept on Feb 13 makes public text of speech made by Sec Shultz at closed session of 13-nation energy conf in which he lists ideas and suggestions for dealing with purely financial problems raised for world by huge increase in price of oil. ... Document nyta000020011127d62f07et9
我们可以观察到以下模式:
如果您的文本文件结构非常严格和一致,即每个信息字段总是出现在固定的行号上,那么可以采用一种简单直接的行号索引方法。这种方法实现起来较为简单,但对格式变化非常敏感。
import pandas as pd
def extract_text_info_fixed(text):
"""
根据固定行号从文本中提取信息。
此方法要求文本结构高度一致。
"""
lines = text.strip().split('\n')
# 确保行数足够,避免索引越界
section_title = lines[1].strip() if len(lines) > 1 else None
word_count = int(lines[3].split()[0]) if len(lines) > 3 and lines[3].strip().endswith("words") else None
date = lines[4].strip() if len(lines) > 4 else None
news_source = lines[5].strip() if len(lines) > 5 else None
# 注意:此固定行号方法未包含语言和完整内容,因为它们的位置不固定或需要更复杂的逻辑
# 语言可能在第7行,但如果中间有其他可选行,则会错位
# 完整内容则需要更复杂的段落识别逻辑
info = {
"Section": section_title,
"Word Count": word_count,
"Date": date,
"News Source": news_source,
# "Language": None, # 无法通过固定行号可靠提取
# "Content": None # 无法通过固定行号可靠提取
}
return info
# 示例:使用多个文本片段进行测试
list_of_texts = [
"""
Section
US Treas Dept on Feb 13 makes public text of speech made by Sec Shultz at...
228 words
15 February 1974
New York Times Abstracts
NYTA
Pg. 1, Col. 1
English
c. 1974 New York Times Company
US Treas Dept on Feb 13 makes public text of speech made by Sec Shultz at closed session of 13-nation energy conf in which he lists ideas and suggestions for dealing with purely financial problems raised for world by huge increase in price of oil. ...
Document nyta000020011127d62f07et9
""",
"""
Section
Another Section in your texts
99999 words
24 March 2023
Forbes
...
Pg. 1, Col. 1
...
...
This is the content for another section. It can be quite long and span multiple paragraphs.
It might also have some special characters or formatting.
Document doc_id_12345
"""
]
# 存储解析结果
data_list_fixed = []
for text in list_of_texts:
result = extract_text_info_fixed(text)
if result:
data_list_fixed.append(result)
# 转换为Pandas DataFrame
df_fixed = pd.DataFrame(data_list_fixed)
print("--- Fixed-Line Parsing Results ---")
print(df_fixed)注意事项:
对于半结构化文本,正则表达式(Regex)是更强大和灵活的工具。它允许我们通过模式匹配来定位和提取信息,即使文本中存在一些变化或可选字段。我们将构建一个综合的正则表达式来一次性捕获所有目标字段。
import re
import pandas as pd
def parse_factiva_text_regex(text):
"""
使用正则表达式从Factiva文本中提取文章信息。
此方法对文本结构的变化具有更好的鲁棒性。
"""
# re.DOTALL 允许 '.' 匹配包括换行符在内的任何字符
# re.VERBOSE 允许在正则表达式中使用空格和注释,提高可读性
pattern = re.compile(r"""
Section\s*\n # "Section" 关键字后跟可选空格和换行
(?P<section_title>.*?)\n\n # 捕获文章标题,直到两个换行符
(?P<word_count>\d+)\s+words\n # 捕获字数
(?P<date>\d{1,2}\s+\w+\s+\d{4})\n # 捕获日期 (e.g., 15 February 1974)
(?P<news_source>.*?)\n # 捕获新闻来源 (多词)
(?:NYTA\n)? # 可选的 'NYTA' 行 (非捕获组)
(?:Pg\.\s*\d+,\s*Col\.\s*\d+\n)? # 可选的页面/列信息行 (非捕获组)
(?P<language>.*?)\n # 捕获语言
(?:c\.\s*\d{4}\s+.*?Company\n)? # 可选的版权信息行 (非捕获组)
\n # 元数据与正文之间的空行
(?P<content>.*?) # 捕获文章正文 (非贪婪匹配)
(?:Document\s+.*)? # 可选的文档ID行 (非捕获组)
""", re.VERBOSE | re.DOTALL)
match = pattern.search(text)
if match:
data = match.groupdict()
# 对捕获到的数据进行清洗和类型转换
data['section_title'] = data['section_title'].strip()
data['word_count'] = int(data['word_count'])
data['news_source'] = data['news_source'].strip()
data['language'] = data['language'].strip()
data['content'] = data['content'].strip()
return data
return None
# 示例:使用上述定义的文本片段进行测试
data_list_regex = []
for text in list_of_texts:
result = parse_factiva_text_regex(text)
if result:
data_list_regex.append(result)
# 转换为Pandas DataFrame,并重命名列以符合要求
df_regex = pd.DataFrame(data_list_regex)
df_regex.rename(columns={
'section_title': 'Section',
'word_count': 'Word Count',
'date': 'Date',
'news_source': 'News Source',
'language': 'Language',
'content': 'Content'
}, inplace=True)
print("\n--- Regex Parsing Results ---")
print(df_regex)代码解释:
以上就是将半结构化文本解析为Pandas DataFrame的实用指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号