【发布时间】:2016-05-21 03:15:39
【问题描述】:
我正在编写一个程序来拆分标签中包含的单词。
例如我想拆分主题标签:
#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
为什么会这样?特别是我使用了this answer 的建议,但我不明白这段代码出了什么问题。
【问题讨论】:
-
嗯.. 有什么问题。为什么投反对票?这是关于编程!
-
综合性很好,但您的问题至少应该是可读的。使用英语句子而不是像“aim: do this. Code: ..; output ..; why?see here”这样的摘要。
-
@Bakuriu 感谢您的编辑!我会记住再问一次。
-
我只是想举例说明如何写一个好问题。你在提供完整的代码以及你所期望的输出方面做得很好,但是你应该至少放一段文字来描述你想要做什么(也许是为什么,一点背景)以及代码如何适应这个。这样你的问题会更有吸引力,更有用。
标签: python regex string replace hashtag