中的字符串索引超出范围问题

2024-10-01 22:31:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我制作了这个简单的脚本来练习正则表达式,它应该读取我复制到剪贴板上的文本,并计算“corona”一词被提及的次数。但我一直在

"IndexError: string index out of range" which I get at matches.append(groups[0])

我不明白,因为我从0开始索引

import re
import pyperclip

coronaRegEx = re.compile(r'Corona(virus)*', re.IGNORECASE)

text = str(pyperclip.paste())
matches = []
count = sum(matches)

for groups in coronaRegEx.findall(text):
    matches.append(groups[0])

if len(matches) > 0:
    pyperclip.copy(join(matches))
    print("Found " + count + " of instances")
else:
    print("No instances found")

Tags: ofinstancestext文本importre脚本count
1条回答
网友
1楼 · 发布于 2024-10-01 22:31:22

我不知道你对这个问题的看法。我已简化为以下内容

import re
#import pyperclip
#I don't know what clipboard pasting you are doing so I have skipped pyperclip 
text = "Corona(virus) adsfj rl Corona adfs Corona adf Corona dfsd Corona Corona(virus) dfs asdf"
matches = []

for group in re.findall('Corona[virus]*',text):
    matches.append(group)

print(matches)

if len(matches) > 0:
    print("Found " + str(len(matches)) + " of instances")
else:
    print("No instances found")

看看这是否解决了你的问题。(这也处理空字符串角的情况)

相关问题 更多 >

    热门问题