我刚刚读了一堆关于如何在Python语言中处理StopIteration错误的文章,但我在解决我的特定示例时遇到了麻烦。基本上,我有一个带有很多前缀的csv文件。此文件有两列标题: Word和Count。Count是该前缀出现的频率。我还有另一个包含公司名称列表的文件。前缀文件从公司文件中每个公司名称的第一个单词获取前缀。我正在尝试删除重复项,现在我想做的是:
每次发生此错误时,请忽略StopIteration错误。
换句话说,我不需要写下所有注释掉的" if“语句,我只需要一行代码:如果生成了StopIteration错误,简单地忽略错误是一种方法,方法是把有问题的”前缀“当作在前缀文件中出现两次以上的前缀,这样我们就应该返回公司名称的值,而不包括前缀。我意识到这忽略了一个事实,即在前缀文件中有一个不同的前缀值和公司名称的实际前缀,但通常它与非美国英语字母在python和excel之间存储的不同有关,以及其他一些看起来不是特别系统化的方式,所以我稍后将手动删除它们。
我的代码是:
def remove_prefix(prefix, first_name):
#try:
#EXCEPTIONS:
#if '(' in prefix:
# prefix = prefix[1:]
#if ')' in prefix:
# prefix = prefix[:-1]
"""
if prefix == "2-10":
prefix = "2"
if prefix == "4:2:2":
prefix = "4"
if prefix == "5/0" or prefix == "5/7" or prefix == "58921-":
prefix = "5"
"""
#except StopIteration:
# pass
print(first_name, prefix)
input_fields = ('Word', 'Count')
reader = csv.DictReader(infile1, fieldnames = input_fields)
#if the prefix has a frequency of x >=2 in the prefix file, then return first_name without prefix
#else, return first_Name
infile1.seek(0)
#print(infile1.seek(0))
next(reader)
first_row = next(reader)
while prefix != first_row['Word'] and prefix[1:]!= first_row['Word']:
first_row = next(reader)
#print(first_name, prefix)
#print(first_row, first_name, prefix, '\t' + first_row['Word'], prefix[1:])
if first_row['Count'] >= 2:
length = len(prefix)
first_name = first_name[length+1:]
#print("first name is ", first_name)
return first_name发布于 2012-09-01 03:39:50
这可以通过一种简单得多的方式完成,方法是首先从文件创建一个前缀列表,然后对每个前缀使用startswith方法。例如:
reader = csv.DictReader(infile1)
# # this is assuming there are only two columns in the file: Word and Count
prefixes = [l["Word"] for l in list(reader) if int(l["Count"]) >= 2]
def remove_prefix(first_name):
for p in prefixes:
if first_name.startswith(p):
return first_name[len(p):]
return first_name这不是更简单吗?另一个优点是,它只读取文件一次,而不是重新打开它想要替换的每个单词。
发布于 2012-09-01 03:47:08
我不认为这是由你所认为的原因造成的。当生成器(reader)读取的行数不足时,会导致StopIteration异常。
例如:
def g():
"generates 1 (once)"
yield 1
a = g()
next(a) # is 1
next(a) # StopIteration exception (nothing left to yield)要解决此问题,您可以在try中包装next,除了(pass):
while prefix != first_row['Word'] and prefix[1:]!= first_row['Word']:
try:
first_row = next(reader)
except StopIteration:
pass然而,正如David所指出的,这可能不是您应该采用的方式。
https://stackoverflow.com/questions/12221443
复制相似问题