创建从字符串输入中删除停止字的代码时遇到问题目前,我的代码是:
stopWords = [ "a", "i", "it", "am", "at", "on", "in", "to", "too", "very", \
"of", "from", "here", "even", "the", "but", "and", "is", "my", \
"them", "then", "this", "that", "than", "though", "so", "are" ]
stemEndings = [ "-s", "-es", "-ed", "-er", "-ly" "-ing", "-'s", "-s'" ]
punctuation = [ ".", ",", ":", ";", "!", "?" ]
line = raw_input ("Type in lines, finish with a . at start of line only:")
while line != ".":
def remove_punctuation(input): #removes punctuation from input
output = ""
text= 0
while text<=(len(input)-1) :
if input[text] not in punctuation:
output=output + input[text]
text+=1
return output
newline= remove_punctuation(line)
newline= newline.lower()
可以添加哪些代码来根据上面的停止字列表从字符串中删除停止字?提前谢谢你。
最佳答案
正如greg建议的那样,应该使用for
循环而不是while
循环,因为它更像是python,而且更易于理解代码另外,您应该在输入的while
循环之前声明函数,这样python解释器就不会每次都重新定义函数了!
此外,如果需要,可以将标点设置为astring
,而不是alist
(以便于阅读和使用)
stopWords = [ "a", "i", "it", "am", "at", "on", "in", "to", "too", "very", \
"of", "from", "here", "even", "the", "but", "and", "is", "my", \
"them", "then", "this", "that", "than", "though", "so", "are" ]
stemEndings = [ "-s", "-es", "-ed", "-er", "-ly" "-ing", "-'s", "-s'" ]
punctuation = ".,:;!?"
def remove_punctuation(input_string):
for item in punctuation:
input_string = input_string.replace(item, '')
return input_string
line = raw_input ("Type in lines, finish with a . at start of line only:")
while not line == ".":
newline = remove_punctuation(line)
newline = newline.lower()