检查字符串是否格式化单词

时间:2018-03-07 09:33:09

标签: python machine-learning text-classification

我正在构建一个python文本分类应用程序。在应用程序中,用户提供一个小句子(或单个单词),我们将他的句子分类。我面临的问题是找到一种方法来检查他的字符串是否格式化一个单词或一组单词。

用户输入示例:

1)“asdfasdfa”

2)“这是adsfgafdga”

示例1不是单词所以我想引发错误,示例2中也包含非单词字符串,所以我也想提出错误。

正确的例子:

1)“你好”

2)“这很好”

有没有办法在没有单词列表或有人知道API的情况下这样做?

3 个答案:

答案 0 :(得分:2)

一种广泛的方法是创建一个列表并将字典单词存储在其中。首先对用户输入执行拆分,以使用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代替列表。

对于更复杂的解决方案,您可以尝试合并PyEnchant之类的API来设置拼写检查库。有关这方面的更多详细信息,您可以查看并执行pip install pyenchant并导入它。

>>> import enchant
>>> help(enchant)

答案 1 :(得分:0)

这将使用空格分割字符串,我们将计算字符串中由空格分隔的字符分组数。如果此列表的长度为1,那么我们在字符串输入中只有一个单词。

string = "This is adsfgafdga"
if len(string.split()) == 1:
    is_word = True
else: is_word = False

答案 2 :(得分:0)

您可以按如下方式使用正则表达式:

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
相关问题