【问题标题】:How do i print the whole string in "startswith" method如何在“startswith”方法中打印整个字符串
【发布时间】:2020-06-07 21:05:02
【问题描述】:

例如:来自 stephen.marquard@uct.ac.za 2008 年 1 月 5 日星期六 09:14:16。
我想从文本文件中提取这一行:mbox-short.txt

下面的示例代码仅提取:来自 stephen.marquard@uct.ac.za 而不是 TIME 的整行

代码:

fh = open(fname)
di = dict()
for email in fh :
    if not email.startswith ('From:'): continue
    print(email)

【问题讨论】:

  • 可以添加文件mbox-short.txt的内容吗?
  • 看来你的内容不只是在线,因为你什么都没做删除东西

标签: python


【解决方案1】:

您是否观察到您的文件在From 之后没有":" 而您的代码有。假设是这种情况,您可能希望运行以下代码并且它会起作用。

fh = open(fname)
di = dict()
for email in fh :
    if not email.startswith ('From'): continue
    print(email)

如果这不起作用,您可能希望共享输入文件的内容或文件本身,以便我们尝试提供帮助。

【讨论】:

  • @Bulelani:有用吗?您的反馈将不胜感激。
【解决方案2】:

最好使用上下文管理器:

with open(fname) as fh:
    di = dict()
    for email in fh :
        if email.startswith('From:'): print(email)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多