“无法分解”;字符串。替换“字符串”;用Python
我被安排了一道计算机科学实验题,我真的很难掌握它。。为了便于学习,我们不允许使用“内置”函数,即本例中的“string.replace()” 我已经定义了一个从输入字符串中删除“停止字”的函数,但无法使其正常工作,有人看到下面发生的任何问题吗 干杯“无法分解”;字符串。替换“字符串”;用Python,python,Python,我被安排了一道计算机科学实验题,我真的很难掌握它。。为了便于学习,我们不允许使用“内置”函数,即本例中的“string.replace()” 我已经定义了一个从输入字符串中删除“停止字”的函数,但无法使其正常工作,有人看到下面发生的任何问题吗 干杯 import string text = raw_input ( " Please Enter Here: ") def removePunctuation(text_input): line = [] i = 0 tota
import string
text = raw_input ( " Please Enter Here: ")
def removePunctuation(text_input):
line = []
i = 0
total_text = ""
new_char_string = ""
for char in text_input:
if char in string.punctuation:
char = ""
new_char_string = new_char_string + char
line = line + [new_char_string.lower()]
total_text = (total_text + new_char_string).lower()
return line
打印删除标点符号(文本)仅供参考,当stop_单词是元组时,stop_单词中的
word
可能非常低效(如此处所示);你应该把它做成一套。(这可能与足够短的列表无关,但由于它是O(n),随着列表的增长,性能将线性下降,而Python的设置查找实际上是恒定时间)。第一个错误:for word in text\u input
将返回字符,而不是单词,如果text\u input
是字符串,我强烈建议在算法开始时将字符串转换为(可变)列表,直接修改列表,最后再转换回字符串。Python中的字符串操作相对昂贵——因为字符串是不可变的,它们不能在适当的位置进行修改——所以理想的做法是只进行一次大的连接(如'.join(words)
)。另一个错误:String.split(text)
不应该工作,因为text
在这里不是变量。你的意思是string.split(word)
?如果能看到一个完整的短程序,就像你在机器上运行它一样,一个导致它行为异常的输入行或文件的示例,以及它正在做什么和你期望它做什么的描述,那将非常有帮助。
def removeStopWords(text_input):
line_stop_words = []
stop_words = "a","It","i","it","am","at","on","in","of","to","is","so","too","my","The","the","and","but","are","very","here","even","from","them","then","than","this","that","though"
word = ""
for word in text_input:
word_list = string.split(text_input)
new_string = ""
for word in word_list:
if word in stop_words:
new_string = new_string + word + " "
new_string = string.split(new_string)
line_stop_words = line_stop_words + [new_string]
return(line_stop_words)