【发布时间】:2021-08-29 09:28:23
【问题描述】:
在编写脚本以纠正 OCR 生成的文档中的格式错误时,我遇到了一个问题,根据我首先运行的循环,程序运行速度会慢 80%。
这是代码的简化版本。我有以下循环来检查大写错误(例如“posSible”):
def fixUppercase(doc):
fixedText = ''
for line in doc.split('\n'):
fixedLine = ''
for word in line.split():
if (
word.isalpha()
and (
word.isupper()
or word.istitle()
or word.islower()
)
):
if word == line.split()[-1]:
fixedLine += word + '\n'
else:
fixedLine += word + ' '
elif (
word.isalpha()
):
lower = word.lower()
if word == line.split()[-1]:
fixedLine += lower + '\n'
else:
fixedLine += lower + ' '
else:
if word == line.split()[-1]:
fixedLine += word + '\n'
else:
fixedLine += word + ' '
fixedText += fixedLine
return fixedText
以下循环检查并删除标题:
def headingsFix(doc):
fixedText = ''
count = 0
stopWords = ['on', 'and', 'of', 'as', 'for']
for line in doc.split('\n'):
tokenLine = ''
for word in line.split():
if word not in stopWords:
tokenLine += word + " "
if tokenLine.istitle() and (
not line.endswith('.')
and not line.endswith(',')
and not line.endswith(')')
and not line.endswith(';')
and not line.endswith(':')
):
count += 1
else:
fixedText += line
return fixedText
这是fixedUppercase 函数中的循环大大减慢了速度。如果我在该函数之前运行任何其他函数或循环,或者如果我先运行该函数或完全删除它,则程序很快。如果两个循环都是一个函数的一部分,则行为相同。
我认为可能是另一个函数或循环通过扩展文档的长度导致了错误,但是使用len() 进行检查显示了相同的文档大小。
【问题讨论】:
-
您能否更明确地说明“...如果我在此之前运行任何其他功能或循环,速度会大大降低”?您能否举一个具体的例子,首先运行另一个函数,使那个函数明显变慢?
-
您会在此处找到一些有用的指南来创建最小的可重现示例:stackoverflow.com/help/minimal-reproducible-example 让您了解任何试图回答您的问题的人所面临的问题:1. 我们不知道您的输入 - 它有长线吗?多行?很多话? 2. 我们不知道如何运行你的代码来重现你的问题——我们应该先运行什么其他函数,我们应该怎么做,哪些输入和输出去哪里?
-
嗨,我确实举了一个例子:如果我在 fixUppercase() 之前运行 headingsFix(),后者需要大约 80% 的时间才能完成。附言我知道我可以用正则表达式完成同样的工作,我只是好奇为什么速度差异。
-
嗨 Weeble,输入是字符串。您可以尝试使用任何字符串。观察。字符串越小,时间和差异就越小。 300k字,就是几分钟。只需将一个字符串传递给一个函数,然后传递另一个函数,计时,然后以相反的顺序再次执行。
-
不运行它,这可能很慢,因为它会构建大量字符串,这在 Python 中非常慢,因为字符串是不可变的,因此每次都必须创建一个新的!你可以使用timeit比较Python中函数的速度!
标签: python python-3.x function