6

目前正在学习python并且遇到了一些问题。我正在尝试从另一个子程序中取出一行并将其转换为单独的单词,这些单词除了一些标点符号之外已经被剥离。这个程序的输出应该是它显示的单词和行号。应该看起来像这样 -> 单词:[1]

输入文件:

please. let! this3 work.
I: hope. it works
and don't shut up

代码:

    def createWordList(line):
        wordList2 =[]
        wordList1 = line.split()
        cleanWord = ""
        for word in wordList1: 
            if word != " ":
                for char in word:
                    if char in '!,.?":;0123456789':
                        char = ""
                    cleanWord += char
                    print(cleanWord," cleaned")
                wordList2.append(cleanWord)
         return wordList2

输出:

anddon't:[3]
anddon'tshut:[3]
anddon'tshutup:[3]
ihope:[2]
ihopeit:[2]
ihopeitworks:[2]
pleaselet:[1]
pleaseletthis3:[1]
pleaseletthis3work:[1]

我不确定这是什么原因造成的,但我学会了 Ada 并在短时间内过渡到 python。

4

2 回答 2

12

当然,你也可以使用正则表达式:

>>> import re
>>> s = """please. let! this3 work.
... I: hope. it works
... and don't shut up"""
>>> re.findall(r'[^\s!,.?":;0-9]+', s)
['please', 'let', 'this', 'work', 'I', 'hope', 'it', 'works', 'and', "don't", 
 'shut', 'up']
于 2012-10-26T16:36:31.643 回答
4

您应该cleanWord在外循环的每次迭代的顶部设置回一个空字符串:

def createWordList(line):
    wordList2 =[]
    wordList1 = line.split()
    for word in wordList1:
        cleanWord = ""
        for char in word:
            if char in '!,.?":;0123456789':
                char = ""
            cleanWord += char
        wordList2.append(cleanWord)
    return wordList2

请注意,我还删除了if word != " ", 因为之后line.split()您将永远不会有空格。

>>> createWordList('please. let! this3 work.')
['please', 'let', 'this', 'work']
于 2012-10-26T16:32:08.117 回答