所以我需要一種方法讓python找到一個字串的匹配項,然后找到前一個單詞。例如:
如果我搜索“abc”:
123 xyz abc def
我得到:
xyz abc
如果這有助于/改變任何事情,我正在搜索的全文是一個請求回應。
我試圖寫一些東西來選擇上一行,但它從未發生過。我洗掉了代碼(我不應該這樣做),因為它不起作用。
uj5u.com熱心網友回復:
您也可以只使用一個簡單的串列推導:
string = input('Enter string to be searched:').split(' ')
search = input('Enter characters to be searched for in string:')
output = ''.join([string[i-1] ' ' string[i] for i in range(len(string)) if string[i] == search])
if len(output) == 0:
print('No matches found')
else:
print('Match found: ' output)
輸出:
Enter string to be searched: 123 xyz abc def
Enter characters to be searched for in string: abc
Match found: xyz abc
uj5u.com熱心網友回復:
一種方法是使用正則運算式來匹配abc并同時捕獲它之前的單詞:
import re
s = '123 xyz abc def'
m = re.search(r'(\w \s abc)', s)
if m is not None:
print(m.group())
輸出:
xyz abc
如果abc可能出現在字串的開頭,并且您仍想匹配,則可以更改正則運算式以允許在開頭進行匹配:
s = 'abc def'
m = re.search(r'((\w \s |^)abc)', s)
if m is not None:
print(m.group())
輸出:
abc
請注意,您可以使用re.findall而不是re.search簡化代碼,例如
m = re.findall(r'((?:\w \s |^)abc)', s)
m將是字串中所有匹配項的串列(如果沒有,則為空)。
uj5u.com熱心網友回復:
獲取單詞串列(假設它們用空格分隔):
s = "123 xyz abc def"
words = s.split()
壓縮這個串列,并將其自身向前移動一個位置,并構建一個字典,其中下一個單詞是鍵,前一個單詞是值:
word_dict = dict(zip(words[1:], words))
# {'xyz': '123', 'abc': 'xyz', 'def': 'abc'}
查字典中的單詞:
word_dict['abc']
#'xyz'
限制:如果字串中有多個感興趣的單詞實體,則該解決方案不起作用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/450107.html
標籤:Python python-3.x
