【问题标题】:In Python, how can I split a .txt file and store just the sections that I want in a list?在 Python 中,如何拆分 .txt 文件并将我想要的部分存储在列表中?
【发布时间】:2013-02-21 05:42:48
【问题描述】:

我对编码非常陌生,我在 SO 上看到了一些类似的问题,但没有一个真正解决了我的问题。 我把它作为一个学习练习开始,认为这将是一项相对容易的任务,但我遇到的麻烦比我想象的要多。

如果我有一个 .txt 文档,其中有几种情况会发生这种情况:

以下答案是可以接受的:
caía

我正在尝试弄清楚如何拆分字符串并将答案添加到列表中。

如果我只处理一个字符串,它会变成这样吗?

    txt = """
    The following answer is acceptable: 
    caía

    more stuff down here...
    """
    list = []
    try = txt.split(": ") # I know this is wrong...  
    # How can I get from the colon (or newline) to the end of the answer?
    list.append(try)

我真的不知道如何从答案的开头抓取到答案的结尾并将其放入列表中。 为了让它更复杂(至少对我来说),因为我正在使用一个带有 6 或 7 个这样的答案的 .txt 文件,我需要弄清楚如何将所有答案添加到列表中。我猜我需要某种循环?使用 txt.readlines 逐行分割?或者我目前不熟悉的东西......

另外,我的计划是经常切换 .txt 文件中的不同文本集。语法将始终保持不变,但答案的数量会有所不同,所以我知道我需要弄清楚如何让程序识别有 n 个答案,并且它应该将所有答案添加到那个我正在谈论的列表,直到它到达文档的末尾。

我知道这个网站对问题非常严格,所以我认为我遵守了所有规则。我只是在学习这些东西,它真的触动了我的激情。我真的没有任何有经验的人可以学习,从书本中学习给我留下了很多问题。我希望这没问题。

【问题讨论】:

  • 您如何知道答案何时结束?有空行吗?
  • 你不应该使用 listtry 作为变量名,这些是保留字。
  • 正如@monkut 所说的listtry 作为变量,如果你真的想将它们作为变量,那么python 会在你的代码上抛出一个合适的值,只需在它们后面添加一个下划线:list_ & try_ 也正如@mtth 所说,您需要一个字符,以便您知道何时停止向列表添加答案,或者列表是否转到文件末尾?
  • 请添加一个更完整的示例以及您想要的输出,目前很难看出您到底想要实现什么......

标签: python string list text split


【解决方案1】:

假设答案之前的那一行只有一行

lines = [line.strip() for line in open('some.txt')]
nlines=[]
for line in lines:
    if line[-1]==':': 
        nlines.append(':'+line)
    else:
        nlines.append(line)
total="\n".join(nlines)
temp=total.split(':')
answers=temp[2::2]
for ans in answers:print ans

一些.txt

first answer:
first line 1
second line 1
third line 1
second answer:
first line 2
secon line 2
third line 2
third answer:
first 3
second 3
third 3
fourth answer:
first 4
second 4
third 4
fourth 4

输出

first line 1
second line 1
third line 1


first line 2
secon line 2
third line 2


first 3
second 3
third 3


first 4
second 4
third 4
fourth 4

【讨论】:

    【解决方案2】:

    你把问题复杂化了。看起来您想要做的是识别一行何时以冒号结尾,如果是,则将值存储在下一行中。

    txt = """
    The following answer is acceptable: 
    caía
    
    more stuff down here...
    """
    results = []
    
    chopped_up_text = txt.split('\n')
    for i, line in enumerate(chopped_up_text):
        if line[-1]==":" :
            results.append(chopped_up_text[i+1])
    

    这有点不雅,但确实有效。

    编辑:关于具有多个枚举答案的问题:

    txt = """
    The following answer is acceptable:
    answer1
    answer2
    answer3
    
    more stuff down here...
    """
    results = []
    
    chopped_up_text = txt.split('\n')
    n=0
    while chopped_up_text:    
        line = chopped_up_text.pop(0)
        try:
            if line.strip()[-1]==":" :
                line = chopped_up_text.pop(0)
                while line not in ("\n", "", " ", None): 
                    results.append(line)
                    line = chopped_up_text.pop(0)
        except:
            continue
    

    时间不早了。这段代码应该更漂亮。但你明白了。

    【讨论】:

    • 我不相信这是他要求的...如果我没记错他要求:txt = """ The following answers are acceptable: caia something something else another something else """
    猜你喜欢
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多