检查一个字符串是否格式化一个单词
Check if a string format a word
我正在构建一个 python 文本分类应用程序。在应用程序中,用户提供一个小句子(或单个单词),我们对其句子进行分类。我面临的问题是想办法检查他的字符串格式是一个词还是一组词。
用户输入示例:
1) "asdfasdfa"
2) "This is adsfgafdga"
示例 1 不是单词,所以我想报错,示例 2 中包含一个非单词字符串,所以我也想报错。
正确的例子:
1) "Hello"
2) "This is good"
有没有办法在没有单词列表或有人知道 API 的情况下做到这一点?
这将使用空格拆分字符串,我们将计算字符串中由空格分隔的字符分组数。如果这个列表的长度是 1,那么我们在字符串输入中只有一个单词。
string = "This is adsfgafdga"
if len(string.split()) == 1:
is_word = True
else: is_word = False
您可以按如下方式使用正则表达式:
import re
# if word is delimited by white space
is_word = len(re.split('[\s]', your_sentence)) ==1
# if word is delimited by non alphanumeric characters
is_word = len(re.split('[^a-zA-Z]', your_sentence)) ==1
一种广泛的方法是创建一个列表并将字典中的单词存储在其中。首先对用户输入执行拆分,使用 phrase.split()
从短语中单独提取每个单词。
words = phrase.split()
// words : ['This', 'is', 'good']
len(words)
// number of words : 3
运行如果结果大于1,则根据词组中单词的个数进行循环。
然后只需使用以下命令检查单词是否存在于列表中即可。
if "word" in dictionary_words:
print "Word is available"
有一个整洁的 XML version of the dictionary words 可以用来代替列表。
对于更复杂的解决方案,您可以尝试合并 API 之类的 PyEnchant 来提供拼写检查库。有关这方面的更多详细信息,您可以查看并执行 pip install pyenchant
并导入。
>>> import enchant
>>> help(enchant)
我正在构建一个 python 文本分类应用程序。在应用程序中,用户提供一个小句子(或单个单词),我们对其句子进行分类。我面临的问题是想办法检查他的字符串格式是一个词还是一组词。
用户输入示例:
1) "asdfasdfa"
2) "This is adsfgafdga"
示例 1 不是单词,所以我想报错,示例 2 中包含一个非单词字符串,所以我也想报错。
正确的例子:
1) "Hello"
2) "This is good"
有没有办法在没有单词列表或有人知道 API 的情况下做到这一点?
这将使用空格拆分字符串,我们将计算字符串中由空格分隔的字符分组数。如果这个列表的长度是 1,那么我们在字符串输入中只有一个单词。
string = "This is adsfgafdga"
if len(string.split()) == 1:
is_word = True
else: is_word = False
您可以按如下方式使用正则表达式:
import re
# if word is delimited by white space
is_word = len(re.split('[\s]', your_sentence)) ==1
# if word is delimited by non alphanumeric characters
is_word = len(re.split('[^a-zA-Z]', your_sentence)) ==1
一种广泛的方法是创建一个列表并将字典中的单词存储在其中。首先对用户输入执行拆分,使用 phrase.split()
从短语中单独提取每个单词。
words = phrase.split()
// words : ['This', 'is', 'good']
len(words)
// number of words : 3
运行如果结果大于1,则根据词组中单词的个数进行循环。 然后只需使用以下命令检查单词是否存在于列表中即可。
if "word" in dictionary_words:
print "Word is available"
有一个整洁的 XML version of the dictionary words 可以用来代替列表。
对于更复杂的解决方案,您可以尝试合并 API 之类的 PyEnchant 来提供拼写检查库。有关这方面的更多详细信息,您可以查看并执行 pip install pyenchant
并导入。
>>> import enchant
>>> help(enchant)