我需要逐行读取一个大文件.假设文件超过5GB,我需要读取每一行,但显然我不想使用,readlines()因为它会在内存中创建一个非常大的列表.
以下代码如何适用于此案例?xreadlines本身是一个一个地读入记忆吗?是否需要生成器表达式?
f = (line for line in open("log.txt").xreadlines()) # how much is loaded in memory?
f.next()
Run Code Online (Sandbox Code Playgroud)
另外,我可以做什么来以相反的顺序读取它,就像Linux tail命令一样?
我发现:
http://code.google.com/p/pytailer/
和
两者都运作得很好!
我有这样的文字:
text = """<div>
<h1>Title</h1>
<p>A long text........ </p>
<a href=""> a link </a>
</div>"""
Run Code Online (Sandbox Code Playgroud)
使用纯Python,没有外部模块我想要这个:
>>> print remove_tags(text)
Title A long text..... a link
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用lxml.html.fromstring(text).text_content()来实现它,但我需要在纯Python中使用内置或std库实现相同的2.6+
我怎样才能做到这一点?
我知道这有充分的理由,但我想知道是什么原因?
>>> print all([])
True
Run Code Online (Sandbox Code Playgroud)
如果all()旨在检查iterable上的每个项是否评估为"True",并且我们知道空列表被评估为False
>>> bool([])
False
Run Code Online (Sandbox Code Playgroud)
那么为什么all()为空列表返回True?
<编辑>
我已经阅读了文档,我知道实现
def all(iterable):
for element in iterable:
if not element:
return False
return True
Run Code Online (Sandbox Code Playgroud)
但问题是为什么不呢?
def all(iterable):
if not iterable:
return False
for element in iterable:
if not element:
return False
return True
Run Code Online (Sandbox Code Playgroud)
这有一个逻辑吗?如果你有一个完成任务列表
today_todo_status = [task.status for task in my_todo if task.date == today]
can_i_go_home = all(today_todo_status)
Run Code Online (Sandbox Code Playgroud)
好吧,在上面的假设例子中,如果我没有任务,那真的很有道理,所以我可以回家了.
但还有其他情况,我不认为所有()都是为todo列表制作的.LOL
</ edit>
在我的项目manage 中,我将 iPython 嵌入到:
from IPython import start_ipython
from traitlets.config import Config
c = Config()
c.TerminalInteractiveShell.banner2 = "Welcome to my shell"
c.InteractiveShellApp.extensions = ['autoreload']
c.InteractiveShellApp.exec_lines = ['%autoreload 2']
start_ipython(argv=[], user_ns={}, config=c)
Run Code Online (Sandbox Code Playgroud)
它运行良好并打开我的 iPython 控制台,但要离开 ipython,我只需键入exit或exit()或按ctrl+D。
我想要做的是添加一个命令exit hook或用exit其他命令替换该命令。
假设我有一个功能。
def teardown_my_shell():
# things I want to happen when iPython exits
Run Code Online (Sandbox Code Playgroud)
当我exit或什至如何exit执行该函数时,如何注册要执行的函数?
注意:我试图通过user_ns={'exit': teardown_my_shell}但不起作用。
谢谢。
我有一个像这样的字符串:
classname = "Recipe"
Run Code Online (Sandbox Code Playgroud)
现在我有一个模块"contenttype.py",我想做这样的事情:
import contenttype
myobject = contenttype.__getobject__(classname)(param=value)
Run Code Online (Sandbox Code Playgroud)
是否有与getattribute类似的东西用于模块的顶层?
我知道我可以用exec()来做,但我试图避免这种情况.
谢谢
编辑:
我找到了一种方法,但我不相信它是好的.
import inspect
myobject = dict(inspect.getmembers(contenttype))[classname](param=value)
Run Code Online (Sandbox Code Playgroud)