骨灰级小白求助!零基础python初学 求好心人!!!

sentence = 'We have some delightful new food in the cafeteria. Awesome!!!' positive_words = ['awesome','good','nice','super','fun'] negative_words = ['awful', 'lame', 'horrible', 'bad'] positive_words.append('delightful') del sentence1 print(sentence) sentence1=sentence.lower() print(sentence1) import string for i in range(len(sentence1)): if sentence[i] in string.punctuation: sentence1=sentence1.replace(sentence[i],'') print(sentence1) 以上运行是不报错的 The code above works well 但当我把上述代码写成函数的形式,它就报了“string index out of range”这个错误 But when i paraphrased them to function form, it reported me the error of "string index out of range" 我改写后的代码如下(Here is the code I paraphrased) def calSent(a,b,c): a1=a.lower() print(a1) import string for m in range(len(a1)): if a1[m] in string.punctuation: a1=a1.replace(a1[m],'') a2=a1.split() count=0 pos=[] neg=[] for i in a2: if i in b: pos.append(i) elif i in c: neg.append(i) else: continue calSent(sentence,positive_words,negative_words) 我不明白这是为什么(I really don't know why is that) Can anyone help me with that? i am at the very beginning and this problem seems to be a really tough one because i checked and checked and i just couldn't find what went wrong.(Even though it might be a really simple problem)

评论 3

  • <p>兄弟,我给你的代码优化了下。 import string sentence = 'We have some delightful new food in the cafeteria. Awesome!!!' positive_words = ['awesome','good','nice','super','fun'] negative_words = ['awful', 'lame', 'horrible', 'bad'] positive_words.append('delightful')</p> <h1 id="del-sentence1">#del sentence1</h1> <p>print(sentence) sentence1=sentence.lower() print(sentence1)</p> <p>for i in range(len(sentence1)): if sentence[i] in string.punctuation: sentence1=sentence1.replace(sentence[i],'') print(sentence1)</p> <pre class="codehilite"><code>这样可以执行,并没有报错,del那句话没有必要写。</code></pre>