簡體   English   中英

在Python中使用函數作為re.sub的參數?

[英]Using a function as argument to re.sub in Python?

我正在編寫一個程序來拆分標簽中包含的單詞。

例如,我想拆分主題標簽:

#Whatthehello #goback

成:

What the hello go back

re.sub與功能參數一起使用時遇到麻煩。

我寫的代碼是:

import re,pdb

def func_replace(each_func):
    i=0
    wordsineach_func=[] 
    while len(each_func) >0:
        i=i+1
        word_found=longest_word(each_func)
        if len(word_found)>0:
            wordsineach_func.append(word_found)
            each_func=each_func.replace(word_found,"")
    return ' '.join(wordsineach_func)

def longest_word(phrase):
    phrase_length=len(phrase)
    words_found=[];index=0
    outerstring=""
    while index < phrase_length:
        outerstring=outerstring+phrase[index]
        index=index+1
        if outerstring in words or outerstring.lower() in words:
            words_found.append(outerstring)
    if len(words_found) ==0:
        words_found.append(phrase)
    return max(words_found, key=len)        

words=[]
# The file corncob_lowercase.txt contains a list of dictionary words
with open('corncob_lowercase.txt') as f:
    read_words=f.readlines()

for read_word in read_words:
    words.append(read_word.replace("\n","").replace("\r",""))

例如,當使用以下功能時:

s="#Whatthehello #goback"

#checking if the function is able to segment words
hashtags=re.findall(r"#(\w+)", s)
print func_replace(hashtags[0])

# using the function for re.sub
print re.sub(r"#(\w+)", lambda m: func_replace(m.group()), s)

我得到的輸出是:

What the hello
#Whatthehello #goback

這不是我期望的輸出:

What the hello
What the hello go back

為什么會這樣呢? 特別是,我已經使用了此答案中的建議,但是我不明白這段代碼出了什么問題。

注意, m.group()返回匹配的整個字符串,無論它是否是捕獲組的一部分:

In [19]: m = re.search(r"#(\w+)", s)

In [20]: m.group()
Out[20]: '#Whatthehello'

m.group(0)還會返回整個匹配項:

In [23]: m.group(0)
Out[23]: '#Whatthehello'

相反, m.groups()返回所有捕獲組:

In [21]: m.groups()
Out[21]: ('Whatthehello',)

m.group(1)返回第一個捕獲組:

In [22]: m.group(1)
Out[22]: 'Whatthehello'

因此,在你的代碼的問題,使用來源於m.group

re.sub(r"#(\w+)", lambda m: func_replace(m.group()), s)

以來

In [7]: re.search(r"#(\w+)", s).group()
Out[7]: '#Whatthehello'

而如果您使用.group(1) ,您將獲得

In [24]: re.search(r"#(\w+)", s).group(1)
Out[24]: 'Whatthehello'

和前面的#會帶來所有不同:

In [25]: func_replace('#Whatthehello')
Out[25]: '#Whatthehello'

In [26]: func_replace('Whatthehello')
Out[26]: 'What the hello'

因此,將m.group()更改為m.group(1) ,然后將/usr/share/dict/words corncob_lowercase.txtcorncob_lowercase.txt

import re

def func_replace(each_func):
    i = 0
    wordsineach_func = []
    while len(each_func) > 0:
        i = i + 1
        word_found = longest_word(each_func)
        if len(word_found) > 0:
            wordsineach_func.append(word_found)
            each_func = each_func.replace(word_found, "")
    return ' '.join(wordsineach_func)


def longest_word(phrase):
    phrase_length = len(phrase)
    words_found = []
    index = 0
    outerstring = ""
    while index < phrase_length:
        outerstring = outerstring + phrase[index]
        index = index + 1
        if outerstring in words or outerstring.lower() in words:
            words_found.append(outerstring)
    if len(words_found) == 0:
        words_found.append(phrase)
    return max(words_found, key=len)

words = []
# corncob_lowercase.txt contains a list of dictionary words
with open('/usr/share/dict/words', 'rb') as f:
    for read_word in f:
        words.append(read_word.strip())
s = "#Whatthehello #goback"
hashtags = re.findall(r"#(\w+)", s)
print func_replace(hashtags[0])
print re.sub(r"#(\w+)", lambda m: func_replace(m.group(1)), s)

版畫

What the hello
What the hello gob a c k

因為,, 'gob''go'


您可以調試的一種方法是將lambda函數替換為常規函數,然后添加print語句:

def foo(m):
    result = func_replace(m.group())
    print(m.group(), result)
    return result

In [35]: re.sub(r"#(\w+)", foo, s)
('#Whatthehello', '#Whatthehello')   <-- This shows you what `m.group()` and `func_replace(m.group())` returns
('#goback', '#goback')
Out[35]: '#Whatthehello #goback'

那會集中您的注意力

In [25]: func_replace('#Whatthehello')
Out[25]: '#Whatthehello'

然后可以與之比較

In [26]: func_replace(hashtags[0])
Out[26]: 'What the hello'

In [27]: func_replace('Whatthehello')
Out[27]: 'What the hello'

這將導致您提出一個問題,如果m.group()返回'#Whatthehello' ,我需要哪種方法返回'Whatthehello' 深入研究文檔即可解決問題。

暫無
暫無

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

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