[英]Python, parse multiple line string extracting characters and digits substring
这是我之前的一个问题的后续,我更清楚地发现了这个问题,我需要一些进一步的建议:)
我有一个字符串,由一些机器学习算法产生,它通常具有以下结构:
像这样的东西:
Connery 3 5 7 @ 4
>> R. Moore 4 5 67| 5 [
我需要提取 2 个名称和数字字符,并检查其中一行是否以特殊字符开头,因此我的输出应该是:。
name_01 = 'Connery'
digits_01 = [3, 5, 7, 4]
name_02 = 'R. Moore'
digits_02 = [4, 5, 67, 5]
selected_line = 2 (anything indicating that it's the second line)
在链接的原始问题中,有人建议我使用:
inp = '''Connery 3 5 7 @ 4
>> R. Moore 4 5 67| 5 ['''
lines = inp.split('\n')
for line in lines:
matches = re.findall(r'\w+', line)
print(matches)
产生的结果非常接近我想要的结果:
['Connery', '3', '5', '7', '4']
['R', 'Moore', '4', '5', '67', '5']
但是我需要将第二行中的前两个字符串('R'、'Moore')组合在一起(基本上,在数字开始之前将所有字符组合在一起)。 并且,它会跳过特殊字符的检测。 我应该以某种方式修复这个输出,还是可以用完全不同的方式解决这个问题?
我不确定您希望保留或删除哪些字符,但以下内容应该适用于该示例:
inp = '''Connery 3 5 7 @ 4
>> R. Moore 4 5 67| 5 ['''
lines = inp.split('\n')
for line in lines:
matches = re.findall(r'(?:[a-zA-Z.][a-zA-Z.\s]+[a-zA-Z.])|\w+', line)
print(matches)
输出:
['Connery', '3', '5', '7', '4']
['R. Moore', '4', '5', '67', '5']
注意。 我包括了az
(下和上)和点,中间有可选的空格: [a-zA-Z.][a-zA-Z.\\s]+[a-zA-Z.]
,但你应该更新到您的真正需要。
这还将包括特殊字符(请记住,它们是硬编码的,因此您必须将缺少的字符添加到正则表达式部分[>@]+
)
for line in lines:
matches = re.findall(r'(?:[a-zA-Z.][a-zA-Z.\s]+[a-zA-Z.])|\w+|[>@]+', line)
print(matches)
这最好分几个步骤完成。
# get the whitespace at start and end out
lines = inp.strip().split('\n')
for line in lines:
# for each line, identify the selection mark, the name, and the mess at the end
# assuming names can't have numbers in them
match = re.match(r'^(\W+)?([^\d]+?)\s*([^a-zA-Z]+)$', line.strip())
if match:
selected_raw, name, numbers_raw = match.groups()
# now parse the unprocessed bits
selected = selected_raw is not None
numbers = re.findall(r'\d+', numbers_raw)
print(selected, name, numbers)
# output
False Connery ['3', '5', '7', '4']
True R. Moore ['4', '5', '67', '5']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.