![](/img/trans.png)
[英]Python, parse multiple line string extracting characters and digits substring
[英]Python, parse string by extracting characters and digits substring
我有一個字符串,由一些機器學習算法產生,通常由多行組成。 在開頭和結尾,可以有一些不包含任何字符的行(空格除外),中間應該有 2 行,每行包含一個單詞,后跟一些數字和(有時)其他字符。
像這樣的東西
first_word 3 5 7 @ 4
second_word 4 5 67| 5 [
我需要提取 2 個單詞和數字字符。
我可以通過執行以下操作來消除空行:
lines_list = initial_string.split("\n")
for line in lines_list:
if len(line) > 0 and not line.isspace():
print(line)
但現在我想知道:
我想 reg 表達式可能很有用,但我從來沒有真正使用過它們,所以我現在有點掙扎
我會在這里使用 re.findall:
inp = '''first_word 3 5 7 @ 4
second_word 4 5 67| 5 ['''
matches = re.findall(r'\w+', inp)
print(matches) # ['first_word', '3', '5', '7', '4', 'second_word', '4', '5', '67', '5']
如果你想單獨處理每一行,那么只需在 CR?LF 上拆分輸入並使用相同的方法:
inp = '''first_word 3 5 7 @ 4
second_word 4 5 67| 5 ['''
lines = inp.split('\n')
for line in lines:
matches = re.findall(r'\w+', line)
print(matches)
這打印:
['first_word', '3', '5', '7', '4']
['second_word', '4', '5', '67', '5']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.