簡體   English   中英

從新行之前的字符串中提取單詞

[英]Extract words from string before new line

我最近問了如何從數字之前的字符串中提取單詞的問題,以幫助我對一些數據進行排序。 這可以完美地工作,直到前面沒有數字並且只有一個新行。

這是由 codenewbie 完成的

import re

strings = '''
Hi my name is hazza 50 test test test

Hi hazza 60 test test test

hazza 50 test test test
'''

for s in strings.split('\n'):
    if s != '':
        print(re.findall('(.+?)\d',s)[0])

這給

Hi my name is hazza 
Hi hazza 
hazza 

這是完美的,但如果字符串前面沒有數字而是換行,則失敗

import re

strings = '''
Hi my name is hazza 50 test test test

Hi hazza 60 test test test

hazza 50 test test test

hazza hazza test test test
'''

for s in strings.split('\n'):
    if s != '':
        print(re.findall('(.+?)\d',s)[0])

我需要它給我

Hi my name is hazza 
Hi hazza 
hazza 
hazza hazza

我努力了

import re

strings = '''
Hi my name is hazza 50 test test test

Hi hazza 60 test test test

hazza 50 test test test

hazza hazza
test test test
'''

    while True:
            try:
                for s in strings.split('\n'):
                    if s != '':
                        print(re.findall('(.+?)\d',s)[0])
            except IndexError:
                print(s.split('/n'))

但不完全確定在哪里插入以及是否有更好的方法

任何幫助將不勝感激

編輯:

例如,我有這些刺痛

Hi my name is hazza 50 test test test

Hi hazza 60 test test test

hazza 50 test test test

hazza hazza
test test test

codenewbie 完成的代碼對前三個字符串工作正常,但對最后一個字符串不工作。

我需要最后一個看起來像

Hi my name is hazza 
Hi hazza 
hazza 
hazza hazza

您可以使用 re.match() [^\d]*匹配任何非數字字符:

import re

strings = '''
Hi my name is hazza 50 test test test

Hi hazza 60 test test test

hazza 50 test test test

hazza hazza test test test
'''

for s in strings.splitlines():
    if s != '':
        print(re.match(r'[^\d]*',s)[0])

印刷:

Hi my name is hazza 
Hi hazza 
hazza 
hazza hazza test test test

編輯:根據評論,新版本:

import re

strings = '''Hi my name is hazza 50 test test test

Hi hazza 60 test test test

hazza 50 test test test

hazza hazza
test test test
'''

for s in re.findall(r'(.*?)(?:\n\n|\n$)', strings, flags=re.S):
    print(re.match(r'(.*?)(?=\d|\n)', s)[0])

印刷:

Hi my name is hazza 
Hi hazza 
hazza 
hazza hazza

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM