0

这是一个更大计划的一部分。这是我想要做的。

  1. 给scan方法传一句话。
  2. 让句子包含数字。
  3. 将句子分成不同的术语。
  4. 将元组附加到列表中,元组中的第一个表达式是单词或句子元素适合的事物类型,第二个是单词或数字。

这是我正在尝试的:

def scan(self, sentence):
    self.term = []

    for word in sentence.split():
        if word in direction:
            self.term.append(('direction', word))
        elif word in verbs:
            self.term.append(('verb', word))
        elif word in stop:
            self.term.append(('stop', word))
        elif word in nouns:
            self.term.append(('noun', word))
        elif type(int(word)) == 'int':
            self.term.append(('number', int(word)))
        else:
            self.term.append(('error', word))

    return self.term



print lexicon.scan('12 1234')

这是一个类中的方法,打印语句在外面。我关心并遇到麻烦的部分是:

elif type(int(word)) == int:
    self.term.append(('number', int(word)))

它应该适用于任何自然数[1,无穷大)

编辑:当我尝试扫描时遇到问题('ASDFASDFASDF')

4

3 回答 3

5

Since you only need positive integers, then try elif word.isdigit(): (note that this will also accept "0").

于 2013-05-20T17:52:58.303 回答
1
if word.lstrip('0').isdigit(): 
    #append

使用.lstrip('0')将删除前导 0 并导致诸如'0'和之类的字符串'000'不通过检查。简单地做if word.isdigit() and word !='0'不会排除'00'或任何其他只是多个'0's 的字符串

您还可以使用try//exceptelse查看它是否为 anint并做出相应的响应

try:
    int(s)
except ValueError:
    print s, 'is not an int'
else:
    print s, 'is an int'
于 2013-05-20T17:54:10.483 回答
0

You could apply int to word and catch a ValueError if it's not a number.

于 2013-05-20T17:52:29.567 回答