![](/img/trans.png)
[英]Grab the first word in a list that is found in a string. ( Python )
[英]Grab first word in string after '\id'
我如何抓住字符串中'\\id '
之后的第一個單詞?
串:
'\id hello some random text that can be anything'
蟒蛇
for line in lines_in:
if line.startswith('\id '):
book = line.replace('\id ', '').lower().rstrip()
我得到什么
book = 'hello some random text that can be anything'
我想要的是
book = 'hello'
一種選擇:
words = line.split()
try:
word = words[words.index("\id") + 1]
except ValueError:
pass # no whitespace-delimited "\id" in the string
except IndexError:
pass # "\id" at the end of the string
>>> import re
>>> text = '\id hello some random text that can be anything'
>>> match = re.search(r'\\id (\w+)', text)
>>> if match:
print match.group(1)
一個更完整的版本,可以捕獲'\\id'
之后'\\id'
空白
re.search(r'\\id\s*(\w+)', text)
您不需要為此的正則表達式,您可以執行以下操作:
book.split(' ')[0]
但是有很多方法可以實現這一目標
如果"\\id"
和單詞之間不必有空格,則regex會很好。 (如果有足夠的空間,請使用拆分解決方案):
import re
match=re.search(r'\\id\s*(\w+)',yourstring)
if match:
print match.group(1)
或另一種方式(不使用正則表達式):
head,sep,tail=yourstring.partition(r'\id')
first_word=tail.split()[1]
嘗試在字符串書上使用str.split(' ')
,它將在空格上分割並提供單詞列表。 然后只需執行book = newList[0]
。
因此book = book.split(' ')[0]
由於您已經檢查了以"\\id "
開頭的行,因此只需拆分字符串即可獲得單詞列表。 如果需要下一個,只需獲取元素1:
>>> line="\id hello some random text that can be anything"
>>> line.split()
['\\id', 'hello', 'some', 'random', 'text', 'that', 'can', 'be', 'anything']
#0 #1 ...
這樣,您的代碼應變為:
for line in lines_in:
if line.startswith('\id '):
book = line.split()[1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.