【问题标题】:How to split the text in a text file from a specific point to another specific point?如何将文本文件中的文本从特定点拆分到另一个特定点?
【发布时间】:2016-02-09 04:47:59
【问题描述】:

我正在寻找的是从文本文件中获取特定的块或段。如何向 Python 指示从哪里开始和完成阅读或打印? 我找到了这个示例代码,但我找不到这种特殊技术的解释。我知道如何对字符串使用“.split()”方法,但还有一些我不明白的附加参数。

a = open("text_1.txt", "r")

text = a.read()

print (text.split("<--")[1].split("-->")[1])

# Here this code splits the text on the text file, starting from
# the value inside of the second ".split()" and ends in the value
# inside the first. What I don't understand what means the one in brackets `[1].`

a.close()

您可能已经注意到,在这种情况下,我要打印的文本位于“--> ..... 和 .....

另外,如果没有符号来分隔文本怎么办?,如果我想隔离整个段落,而不丢失第一个和最后一个单词怎么办?如果在“.split()”方法中指定了多个单词或符号怎么办?

有什么方法可以指示 Python 我想根据其行号选择行(在使用 urllib 导入网页的情况下)?

提前致谢

【问题讨论】:

  • 缩小你的问题范围(!)——特别是你需要什么。

标签: python string text-files urllib


【解决方案1】:

当 python 读取文件时,它会将其转换为列表。拆分是一种字符串方法。这样做的一种方法是将其转换为字符串,然后像您尝试做的那样将其拆分并将其写入文件。检查 dir(list) 和 dir(str) 的方法。

【讨论】:

    【解决方案2】:

    要回答您的几个问题之一,[1] 将第一项(从零开始)从“主要”拉到左侧。在 Python 中,它被称为subscript

    在您的情况下,text.split(...) 返回一个令牌列表,随后的 [1] 只选择其中一个。以下是正在发生的事情:

    >>> 'foo bar baz'.split()
    ['foo', 'bar', 'baz']
    
    >>> 'foo bar baz'.split()[1]
    'bar'
    

    如果您以前没有遇到过这种语法,您可能需要先完成 Python 教程,然后再继续解决您的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      • 2014-02-24
      • 2016-06-06
      相关资源
      最近更新 更多