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

标签 python memory arguments argument-passing saxparser

我正在使用 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/

相关文章:

python - 我对 SQLalchemy declarative_base 使用什么类型?

python - 重新加载模块是否会更改先前导入/重新加载的模块中的名称?

c - "heap"在哪里?

c++ - 通过函数在共享内存中 boost C++ 结构

Python 字符串(参数)-> 正则表达式

r - 将模型公式作为参数传递给 R

bash - 删除最终的 bash 脚本参数

python - 为什么我在 python 中收到此错误? (httplib)

python - 根据 Pandas 数据框中的列标签对数据进行分组

sqlite sqlite3_close()不会释放获取的内存