J'écris un programme pour diviser les mots contenus dans un hashtag.Utiliser une fonction comme argument pour re.sub dans Python?
Par exemple, je veux diviser les hashtags:
#Whatthehello #goback
dans:
What the hello go back
Je vais avoir des problèmes lors de l'utilisation re.sub
avec un argument fonctionnel.
Le code que j'ai écrit est:
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",""))
Par exemple lorsque vous utilisez ces fonctions comme celle-ci:
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)
La sortie est-je obtenir:
What the hello
#Whatthehello #goback
Ce qui est pas la sortie que j'avais prévu:
What the hello
What the hello go back
Pourquoi cela se produit-il? En particulier, j'ai utilisé la suggestion de this answer mais je ne comprends pas ce qui ne va pas dans ce code.
Hmmm .. quel est le problème. Pourquoi la downvote? Il s'agit de programmation !! –
C'est bon d'être syntéthique mais votre question devrait au moins être lisible. Utilisez des phrases en anglais et non des résumés tels que "but: do this Code: ..; output ..; pourquoi? Voir ici". – Bakuriu
@Bakuriu Merci pour le montage! Je le ferai en me demandant à nouveau. –