Ash
Ash

Reputation: 43

How to print a line from a text file without a certain character

Not quite sure if this question is a duplicate, but it seems like it isn't, after searching for a fair while.

Let's say I have these lines of text in text file.

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

The correct answer, B) = *2, is written with a * mark over the line. How would you print this line, but without the character, so the line would be printed like so:

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

I am still new to Python, but I understand that:

print lines[3]

Would print the specific line. Yet I would like to know how to print a line, without a certain character.

Any help and explanation on the Coding, will be much appreciated. Thanks Guys.

Upvotes: 1

Views: 750

Answers (5)

cdarke
cdarke

Reputation: 44354

EDIT: Given this input:

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

There are many ways to tackle this. These are my first thoughts:

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)

Upvotes: 2

The6thSense
The6thSense

Reputation: 8335

you could read the file in for loop itself as the other user has done .By using strip function you can remove the unwanted trialing and leading edges

My code:

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

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

Upvotes: 1

bagrat
bagrat

Reputation: 7418

Assuming you do not have a * in your answer body, just do the following:

>>> 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

Below you may find the definitions:

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

Upvotes: 1

mhawke
mhawke

Reputation: 87074

A * might appear in:

  • the question, e.g. Q5) What is 2*2 seems a likely possibility,
  • as a marker for the correct answer (as shown by OP),
  • elsewhere within an answer (a reasonable assumption)

Blind use of str.replace() on every line of the file is not practical as it will affect all line types possibly corrupting questions and answers.

Maybe a further assumption can be that when * is used to mark the correct answer it will always appear at the same location, i.e. one space after the equals sign, so this might be a better solution:

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

which will replace the first occurrence of ) = * with ) =. It is unlikely that the same sequence of characters would appear elsewhere.

If the whitespace is variable, e.g. tabs mixed with spaces or different numbers of spaces, you can turn to a regular expression like this:

import re

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

Upvotes: 2

Malik Brahimi
Malik Brahimi

Reputation: 16711

You want to print lines without a certain character, right? Just iterate and replace:

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

Upvotes: 1

Related Questions