如何从没有特定字符的文本文件中打印一行

时间:2015-05-18 12:34:20

标签: python python-2.7 printing

不太确定这个问题是否重复,但在搜索公平的时候似乎并非如此。

我们说我在文本文件中有这些文本行。

    Q5) What is 1+1
    A) = 1
    B) = *2
    C) = 0
    D) = -342
    E) = 121

正确答案B) = *2在该行上标有*标记。你将如何打印这一行,但没有这个字符,所以这行将被打印出来:

    Q5) What is 1+1
    A) = 1
    B) = 2
    C) = 0
    D) = -342
    E) = 121

我还是Python新手,但我理解:

print lines[3]

会打印特定行。但我想知道如何打印一条没有特定字符的线条。

有关编码的任何帮助和解释,将不胜感激。谢谢你们。

5 个答案:

答案 0 :(得分:2)

编辑: 鉴于此输入:

Q1) What is 1*1?
   A) = 0
   B) = *1
   C) = 2
   D) = -1
Q2) What is 1-1?
   A) = *0
   B) = 1
   C) = 2
   D) = -1
Q3) What is 1/1?
   A) = 0
   B) = *1
   C) = 2
   D) = -1
Q4) What is 1%1?
   A) = *0
   B) = 1
   C) = 2
   D) = -1
Q5) What is 1+1?
   A) = 1
   B) = *2
   C) = 0
   D) = -342
   E) = 121

有很多方法可以解决这个问题。这是我的第一个想法:

import re

def ask_user(answer):
    user_ans = raw_input("> ").strip()
    if user_ans == answer:
        print "Correct!\n"
        result = True
    else:
        print "Wrong!\n"
        result = False

    return result

question = None

with open('test.txt') as test:
    for line in test:
        if line[0] == 'Q':
            if question:
                ask_user(answer)
            question = line
        else:
            m = re.match(r'(.*?)\*(\d+)', line)
            if m:
                line, answer = m.groups()
                line = "%s%s\n" % (line,answer)

        print line,

# Final question
ask_user(answer)

答案 1 :(得分:2)

*可能会出现在:

  • 这个问题,例如Q5) What is 2*2似乎有可能发生,
  • 作为正确答案的标记(如OP所示),
  • 答案中的其他地方(合理的假设)

在文件的每一行盲目使用str.replace()是不切实际的,因为它会影响可能破坏问题和答案的所有行类型。

也许进一步的假设是,当*用于标记正确答案时,它将始终出现在同一位置,即等号后面的一个空格,因此这可能是更好的解决方案:

line = line.replace(') = *', ') = ', 1)

将用) = *替换) =第一次次出现。不可能在其他地方出现相同的字符序列。

如果空白是可变的,例如与空格或不同数量的空格混合的制表符,您可以转到这样的正则表达式:

import re

pattern = re.compile(r'([A-Z]\)\s+=\s+)\*(.*)$')
line = pattern.sub(r'\1\2', line)

答案 2 :(得分:1)

你想要打印没有特定字符的行,对吧?只需迭代并替换:

for line in data:
    print line.replace('*', '')

答案 3 :(得分:1)

你可以像其他用户一样在for循环中读取文件。使用条带功能你可以删除不需要的试验和前沿

我的代码:

a=open("filename","r")
contents=a.readlines()
i=0
for content in contents:

    print str.strip(content.replace("*",""))
    print i
    i=i+1

答案 4 :(得分:1)

假设您的答案正文中没有*,请执行以下操作:

>>> questions = Question.from_file('your_file.here')
>>> print(questions[0])

Q5) What is 1+1
A) = 1
B) = 2
C) = 0
D) = -342
E) = 121

>>> print(questions[0].correct_answer)

B) = 2

您可以在下面找到定义:

class Question(object):
    def __init__(self, body):
        super(Question, self).__init__()

        self.body = body
        self.answers = []
        self.correct_answer = None

    def add_answer(self, answer, is_correct=False):
        self.answers.append(answer):

        if is_correct:
           self.correct_answer = answer

    def __repr__(self):
        result = self.body + '\n'
        for answer in self.answers:
            result += answer + '\n'

        return result

    @classmethod
    def from_lines(cls, lines):
        question = cls(lines[0])

        for ans_line in lines[1:]:
            body = ans_line
            is_correct = False
            if Answer.CORRECT_MARK in ans_line:
                body = ans_line.replace(Answer.CORRECT_MARK, '')
                is_correct = False
            question.add_answer(Answer(body, question, is_correct))

    @classmethod
    def from_file(cls, filename):
        questions = []
        with open(filename) as q_file:
            lines = q_file.readlines()

            for i in range(0, len(lines), 6):
                questions.append(cls.from_lines(lines[i:i+6]))

class Answer(object):
    CORRECT_MARK = '*'

    def __init__(self, body, question, is_correct=False):
        super(Answer, self).__init__()

        self.body = body
        self.question = question

        question.add_answer(self, is_correct)

    def is_correct(self):
        return self.question.correct_answer == self

    def __repr__(self):
       return self.body