简洁的标点符号并分成单词python

时间:2012-10-26 16:27:56

标签: python word line strip punctuation

目前学习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。

2 个答案:

答案 0 :(得分:7)

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

>>> 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']

答案 1 :(得分:1)

您应该将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']