如何使用find在python中查找近似单词

2024-10-03 23:21:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在许多句子中找到一个单词的第一个字符。所有的句子都有“猜想”这个词的形式,也就是说,猜想,等等。但是我不能像这样在“find”中使用通配符

firstSpace = mySentence.find('conjecture'*,0)

句子看起来像:

^{pr2}$

有什么主意吗?我该怎么做? 谢谢!在


Tags: find字符单词形式句子主意通配符pr2
3条回答

您可以先尝试删除特殊字符:

x = '“ There is considerable conjecture and debate as to how...

newx = ''.join(e for e in x.lower() if e.isalnum())

print newx

>>> 'thereisconsiderableconjectureanddebateastohow'

然后使用find来定位你的单词。在

祝你好运!在

编辑:

如果你想找到你指定单词前面的单词,你可以把句子分开。下面是一段可能有帮助的代码:

^{pr2}$

这样可以得到:

>>> print prev_word_list
>>> ['lazy', 'big', 'furry']

忘记了在后台实际完成的隐性工作,这至少能完成你要求的任务(希望如此)。在

unicodedata.normalize('NFKD', mySentence).encode('ascii', 'ignore').lower().find("conjecture")

老实说,我希望用正则表达式来设置线性搜索,但是unicode值通常被分成两个“字符”。在

相反,这里有一个至少能完成任务的黑客:

^{pr2}$

如果你想忘掉那些讨厌的编码字符:

mySentence.decode("ascii", "ignore").encode("UTF-8").lower().find("conjecture")



Sample input: >>> newStr = "“32f fWF  3(*&(%FJ   conJectuRe€@!O".decode("ascii", "ignore").encode("UTF-8").lower()
              >>> print newStr
              >>> print newStr.find("conjecture")

Output:       '32f fwf  3(*&(%fj   conjecture@!o'
              20

All of the sentences have some form of the word 'conjecture', i.e. conjectures, conjectured, etc.

其他答案中显示的word in string方法通常会失败,例如,在一个含有communities的句子中,他们找不到community这个词。在

在这种情况下,您可能需要一个词干分析算法,如^{} package

from nltk.stem.snowball import EnglishStemmer
from nltk import word_tokenize

stemmer = EnglishStemmer()
stem_word = stemmer.stem

stem = stem_word(u"conjecture")
sentence = u'He conjectured that the interface was...'
words = word_tokenize(sentence)
found_words = [(i, w) for i, w in enumerate(words) if stem_word(w) == stem]
# -> [(1, u'conjectured')]

还有其他的stem和tokenize methods in nltk,您可以根据具体需要使用。在

however some words start with the nasty characters: “ or the like.. how can I get rid of them?

“讨厌的字符”是错误地将utf-8字节序列视为cp1252的结果:

^{pr2}$

你不应该盲目地删除乱码文本,而是修改字符编码。在

Why the #AskObama Tweet was Garbled on Screen: Know your UTF-8, Unicode, ASCII and ANSI Decoding Mr. President显示了这个问题在电视上公开的例子。在

为了理解阅读The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)。在

相关问题 更多 >