gpt4 book ai didi

python - 将内容传递给 Python 中另一个模块的函数

转载 作者:太空宇宙 更新时间:2023-11-03 17:58:36 26 4
gpt4 key购买 nike

我正在使用 SAX 解析器。我正在尝试发送使用以下代码检索到的“内容”:

检查 startElement 和 endElement 后,我​​有以下代码:

def characters(self, content):  
text = format.formatter(content)

此 format.formatter 预计会读取我作为“内容”发送的数据,以进行任何处理(例如删除垃圾字符等)并返回它。我通过使用 string.replace 函数来做到这一点:

    remArticles = {' ! ':'', ' $ ':''}

for line in content:
for i in remArticles:
line= line.replace(i, remArticles[i])
#FormattedFileForIndexing.write(line)
return line

但是输出没有按预期出现。

如果有人能对此提供帮助,那就太好了。

来源将是这样的:

“哦!这可是成千上万的 $$$$”

预期:哦,有很多 1000

最佳答案

您正在迭代每个字符而不是每一行:

def characters(content):
remArticles = {'!': '', '$': ''} # remove spaces from " ! "
for i in remArticles:
content = content.replace(i, remArticles[i])
return content

您还尝试将 !$ 与它们周围的空格匹配,根据您的预期输出,这是不正确的。

In [6]: content =  "Oh! That's lots and 1000s of $$$$"

In [7]: characters(content)
Out[7]: "Oh That's lots and 1000s of "

仅使用替换是最有效的选择:

In [20]: timeit characters(content)
1000000 loops, best of 3: 746 ns per loop

In [21]: timeit format_this(content)
100000 loops, best of 3: 2.57 µs per loop

关于python - 将内容传递给 Python 中另一个模块的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28091913/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com