python - 倒排索引实现中的字符串索引超出范围
问题描述
************************文件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)运行良好。但我想从我的单词中删除特殊字符后缀。
解决方案
您可以使用正则表达式替换(而不是while
循环)来删除非字母字符:
import re
my_word = "Hello_world+?a123"
re.sub(r"(\W|\d|_)+", "", my_word)
#'Helloworlda'
推荐阅读
- combobox - Vuetify 组合框显示 id 而不是 item-text
- github - 将 Github Actions 环境变量注入脚本
- python-3.x - 将 HTTP Post 请求转换为 python 请求
- c - 为什么从函数返回时不能使用方括号语法访问指针的值?
- python - 错误 0 Python PowerBI - 版本问题?
- python - 当 l 是 Python 中的字符串列表时,max(l) 的结果是什么?
- java - 正则表达式 NotBlank 并且不包含 <
- google-data-studio - 谷歌数据工作室嵌入式报告 URL 参数不起作用
- java - 删除 SOAP 信封
- sql - 开始日期保持不变但结束日期发生变化的 SQL 拉取收入期间