学习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.
解决方法:
您应该将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']