首页 > 解决方案 > 倒排索引实现中的字符串索引超出范围

问题描述

************************文件a.py****************************** ********

a=input()
while (not  (a[len(a)-1].isalpha())):
    a=a[:-1]
print(a)

*****************文件b.py的一部分*************************** ******

for my_word in my_words.split():  
    while(not(my_word[len(my_word)-1].isalpha())):  
        my_word=my_word[:-1]  
    ll=lemmatizer.lemmatize(my_word.lower())  
    if ll not in stop_words:  
        l.append(ll) 

文件 a.py 运行良好,但 b.py 给出错误

Traceback (most recent call last):
  File "b.py", line 42, in <module>
    while(not(my_word[len(my_word)-1].isalpha())):
IndexError: string index out of range.

如果我删除 while 循环

while(not(my_word[len(my_word)-1].isalpha())):  
            my_word=my_word[:-1] 

我的代码(b.py)运行良好。但我想从我的单词中删除特殊字符后缀。

标签: pythonstring

解决方案


您可以使用正则表达式替换(而不是while循环)来删除非字母字符:

import re
my_word = "Hello_world+?a123"
re.sub(r"(\W|\d|_)+", "", my_word)
#'Helloworlda'

推荐阅读