1

我对编码很陌生,我在 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 个答案,并且它应该将所有答案添加到那个我正在谈论的列表,直到它到达文档的末尾。

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

4

2 回答 2

0

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

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

晚了。这段代码应该更漂亮。但你明白了。

于 2013-02-21T05:55:37.773 回答
0

假设答案之前的那一行只是单行

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
于 2013-02-21T06:37:31.553 回答