-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.py
More file actions
100 lines (82 loc) · 3.85 KB
/
parser.py
File metadata and controls
100 lines (82 loc) · 3.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"""
输入解析模块
负责严格解析 input_refs.txt 文件,将每条带序号的文献转换为纯净的查询字符串列表。
"""
import re
def parse_input_file(filepath):
"""
解析输入文件,提取文献查询字符串。
参数:
filepath (str): 输入文件路径
返回:
list: 清理后的文献查询字符串列表
"""
queries = []
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
# 使用正则表达式匹配以数字序号开头的行
# 支持多种格式:
# 1. [数字] + 空格 + 内容(如:[17] 内容)
# 2. 数字 + 点号/括号/顿号 + 空格/制表符 + 内容
# 3. 数字 + 制表符 + 内容(如:1\t内容)
# 4. 数字 + 空格 + 内容(如:1 内容)
patterns = [
r'^\s*\[\d+\]\s+(.+)$', # [数字] + 空格 + 内容(优先匹配方括号格式)
r'^\s*\d+[\.\)、]\s+(.+)$', # 数字 + 点号/括号/顿号 + 空格 + 内容
r'^\s*\d+\t+(.+)$', # 数字 + 制表符 + 内容
r'^\s*\d+\s{2,}(.+)$', # 数字 + 多个空格 + 内容
r'^\s*\d+\s+(.+)$', # 数字 + 单个空格 + 内容(最后尝试,避免误匹配)
]
for line in content.split('\n'):
original_line = line
line = line.rstrip() # 只去除右侧空白,保留左侧用于匹配
if not line.strip(): # 跳过空行
continue
query_text = None
# 尝试各种模式匹配
for pattern in patterns:
match = re.match(pattern, line)
if match:
query_text = match.group(1).strip()
if query_text: # 确保不是空字符串
queries.append(query_text)
break
# 如果没有匹配到任何模式,但行不为空,可能是续行或特殊格式
if query_text is None and line.strip():
# 检查是否以[数字]或数字开头(可能是序号格式不标准)
if re.match(r'^\s*\[\d+\]', line) or re.match(r'^\s*\d+', line):
# 尝试提取序号后的所有内容
# 先尝试 [数字] 格式
match = re.match(r'^\s*\[\d+\]\s*(.+)$', line)
if not match:
# 再尝试普通数字格式
match = re.match(r'^\s*\d+\s*(.+)$', line)
if match:
query_text = match.group(1).strip()
if query_text:
queries.append(query_text)
else:
# 如果提取失败,可能是续行,追加到上一个查询
if queries:
queries[-1] += ' ' + line.strip()
else:
# 不是以序号开头,可能是续行
if queries:
queries[-1] += ' ' + line.strip()
else:
# 没有已有查询,直接添加(可能是无序号格式)
queries.append(line.strip())
return queries
except FileNotFoundError:
print(f"错误:找不到文件 {filepath}")
return []
except Exception as e:
print(f"解析文件时出错:{e}")
return []
if __name__ == '__main__':
# 测试代码
test_queries = parse_input_file('input_refs.txt')
print(f"解析到 {len(test_queries)} 条文献查询:")
for i, query in enumerate(test_queries, 1):
print(f"{i}. {query}")