[英]How to skip error and continue to run for loop and continue to the next line
def removepunc(firstlist):
global counti
try:
for words in firstlist:
cleanstr = re.sub(r'[^\w\s]', ' ', words)
counti += 1
print(counti,":", cleanstr)
Appended_Data.to_excel("test.xlsx", index=False)
return(counti,":", cleanstr)
except:
pass
我在这里尝试做的是创建一个函数来从 Excel 工作表中读取一列并删除特殊字符和标点符号,然后将其保存到一个新的 Excel 工作表中。
该列由具有多个句子和特殊字符的字符串组成。 我设法删除了那些特殊字符和标点符号,但是,列中有一行完全是空的。
当代码到达该行(第 506 行)时,它会给出一个错误,指出里面需要有一个字符串或字节。 我使用了 try 和 except 所以错误没有出现,但代码就在那里结束。 如何让它跳过(第 507 行)该行并继续(第 508 行)运行该函数? 提前致谢!
你可以这样做:
def removepunc(firstlist):
global counti
for words in firstlist:
try:
cleanstr = re.sub(r'[^\w\s]', ' ', words)
except:
continue
counti += 1
print(counti,":", cleanstr)
Appended_Data.to_excel("test.xlsx", index=False)
return(counti,":", cleanstr)
您的try
和except
位于错误的位置。
当您在try
块中遇到错误时
for words in firstlist:
cleanstr = re.sub(r'[^\w\s]', ' ', words)
counti += 1
print(counti,":", cleanstr)
Appended_Data.to_excel("test.xlsx", index=False
停止整个块的执行并调用except
块。
except:
pass
这是在函数的末尾,所以函数结束并返回None
为了解决这个问题,将try
块放在cleanstr = re.sub(r'[^\\w\\s]', ' ', words)
周围,而不是pass
ing 使用continue
以便控制返回到循环中的下一个单词。
def removepunc(firstlist):
global counti
for words in firstlist:
try:
cleanstr = re.sub(r'[^\w\s]', ' ', words)
except:
# Not sure if you want to increase counti here
# if so add the line here
continue
counti += 1
print(counti,":", cleanstr)
Appended_Data.to_excel("test.xlsx", index=False)
return(counti,":", cleanstr)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.