如何使用定界符拆分字符串

How to Split String Using Delimiters

我有一个这样命名的文件:

test.txt

dog;cat;mouse;bird;turtle;# just some animals
dog;cat;mouse;bird;turtle;horse cow # just some animals

我需要帮助分解第二行,使其看起来像第一行:

dog;cat;mouse;bird;turtle;horse;cow;# just some animals

困难的部分是它没有关于在第 5 个元素和 '#' 符号前面可以插入多少动物的设置参数。它可能有 2 个,就像我在这个例子中展示的那样,也可能有 10 个。

我可以将所有内容分解为二维数组,但不确定如何拆分第二个字符串。

with open (file) as f:
    lines = list (f)
    temp = [line.strip ().split (';') for line in lines]

输出:

for i in temp:
    print (i)

['dog', 'cat', 'mouse', 'bird', 'turtle', '# just some animals']
['dog', 'cat', 'mouse', 'bird', 'turtle', 'horse cow # just some animals']

期望输出:

['dog', 'cat', 'mouse', 'bird', 'turtle', '# just some animals']
['dog', 'cat', 'mouse', 'bird', 'turtle', 'horse', 'cow', '# just some animals']

感谢任何帮助。

-已更新-

我的实际数据包含以下模式:

10-2-2015;10:02;LOCATION;xxx.xxx.xxx.xxx;xxx.xxx.xxx.xxx;somename1 # more alphanumeric text with caps and lower case
10-2-2015;10:02;LOCATION;xxx.xxx.xxx.xxx;xxx.xxx.xxx.xxx;somename1; somename2 somename3 # more,alphanumeric,text,with,caps,and,lower,case

X 代表 IP 和子网。 '#' 后面的逗号应该保持不变。

找到 # 的索引并从字符串中删除其后的所有内容(包括在内)。然后,找到任何空格(and/or 任何其他需要的字符)并将其设为分号。

您可以试试正则表达式:

>>> import re
>>> my_expression = r'[a-z]+|#.+'
>>> f = 'dog;cat;mouse;bird;turtle;# just some animals'
>>> s = 'dog;cat;mouse;bird;turtle;horse cow # just some animals'
>>> re.findall(my_expression, f)
['dog', 'cat', 'mouse', 'bird', 'turtle', '# just some animals']
>>> re.findall(my_expression, s)
['dog', 'cat', 'mouse', 'bird', 'turtle', 'horse', 'cow', '# just some animals']

以上将找到一组一个或多个小写字母 ([a-z]+) 或 (|) 的每个实例,一个 hash/pound 符号后跟一个或多个字符 ( #.+).

更新样本数据:

>>> my_expression = r'#.+|[^ ;]+'
>>> f='10-2-2015;10:02;LOCATION;xxx.xxx.xxx.xxx;xxx.xxx.xxx.xxx;somename1 # more alphanumeric text with caps and lower case'
>>> s='10-2-2015;10:02;LOCATION;xxx.xxx.xxx.xxx;xxx.xxx.xxx.xxx;somename1; somename2 somename3 # more,alphanumeric,text,with,caps,and,lower,case'
>>> my_expression = r'#.+|[^ ;]+'
>>> re.findall(my_expression, f)
['10-2-2015', '10:02', 'LOCATION', 'xxx.xxx.xxx.xxx', 'xxx.xxx.xxx.xxx', 'somename1', '# more alphanumeric text with caps and lower case']
>>> re.findall(my_expression, s)
['10-2-2015', '10:02', 'LOCATION', 'xxx.xxx.xxx.xxx', 'xxx.xxx.xxx.xxx', 'somename1', 'somename2', 'somename3', '# more,alphanumeric,text,with,caps,and,lower,case', '\n']

此表达式查找任何以下内容:hash/pound 符号后跟一个或多个字符 (#.+) 或 (|) 一组一个或多个字符既没有空格也没有分号 ([^ ;]+).