2016-02-09 59 views
0

我想用正則表達式,從而獲得從文本的具體信息,我舉一個例子用半僞〜你還可以回覆我,半僞代碼:我可以在正則表達式中插入變量嗎?

list=["orange","green","grey"] 
text= "The Orange is orange" 
for word in list: 
    if word == re.compile(r'word, text): 
      capture Orange in order to have the noun 

當心!我的問題集中在是否有可能使用變量(因爲以上),以便進行循環,並查看基於列表的文本中是否有相同的單詞。

不要專注於如何捕捉橙色。

+1

答案取決於語言,所以僞代碼不是這樣一個好主意。 – Biffen

+1

我不明白你需要什麼。你想把變量值放在正則表達式模式中?你可以在Python中做're.search('{}'.format(word),text)''。 – gmoshkin

+1

@DimitrisTsoukalas你想搜索* exact *單詞嗎?如果是這樣,爲什麼使用正則表達式呢?你在嘗試做POS標籤嗎?如果是這樣的話,那麼這種方法會讓你感到很痛苦。 – Biffen

回答

0

我認爲Biffen有正確的想法,如果您使用POS標記標記,您處於一個痛苦的世界。無論如何,這可以讓你在你的text可變

for word in list: 
    if word in text: 
     # Do what you want with word 

如果你想使用正則表達式,那麼你可以建立從字符串中的模式,使用括號來捕捉匹配的話。然後使用group()訪問捕獲的模式

for word in list: 

    pattern = re.compile(".*(" + word + ").*") 
    m = re.match(pattern, text) 

    if m: 
     print(m.group(1)) 
相關問題