0

I am trying to use a txt file within my python code but I am unable to do so. The problem asks to print the words which do not have a specific set of characters from the file.

def give():
    fin=open('words2.txt')
    line=fin.readline()
    for line in fin:
        word=line.strip()
        print word
def enter(forbid):
    words=give()
    for letter in words:
        if letter in forbid:
            return False
        else:
            print words

This code does not give a output at all

2
  • 2
    Are you sure you have indented your code correctly in your post? Commented Jul 13, 2016 at 5:04
  • You should correct the indentation and tell exactly what does not work. Does it print anything? Does it raise an exception? Commented Jul 13, 2016 at 5:52

4 Answers 4

3

I think I figured out what you want:

#!/usr/bin/env python2

def give():
    result = []
    with open('words2.txt', mode='rt') as fin:
        for line in fin:
            result += line.split()
    return result

def enter(forbid):
    words = give()
    for w in words:
        if all([letter not in forbid for letter in w]):
            print w


enter("bcdfghjklmst")

using this lorem ipsum (i.e. content from words2.txt):

Eum dicta nihil iste quo minima repudiandae possimus. Provident nam explicabo ut accusantium odit voluptatibus. Animi dolor sit deserunt quisquam perspiciatis aut et voluptas. Repellat quo accusamus sint.

Tempore vero iste rerum. Harum aut rerum qui rerum quis dolores perspiciatis. Quas sed necessitatibus et rerum eum culpa. Autem delectus aut sunt ab officiis sit non voluptatum. Id sequi voluptas qui quo officia officiis placeat voluptatem.

Nemo ipsa illo amet deleniti. Praesentium voluptatum voluptate mollitia quod voluptates beatae. Doloremque molestias nostrum iste possimus veritatis repellendus et dolor. Quidem sit iusto autem et id dicta ut.

Ad earum incidunt officia ea. Et quidem molestiae et facere. Culpa harum veniam illum. Culpa quod porro in et eos adipisci. Sint accusantium est qui inventore minima perferendis. Autem quidem omnis et quia error enim nam.

Distinctio velit ut facere animi delectus. Et deleniti expedita earum nesciunt voluptas ea. In asperiores a nobis occaecati quam qui repellendus molestiae. Excepturi distinctio consequatur commodi est velit sit. Sit soluta a adipisci aut. Eos voluptatibus enim corrupti.

output (all word not containing any letter from "bcdfghjklmst"):

$ ./test_script2.py
quo
quo
vero
qui
non
qui
quo
ea.
porro
in
qui
quia
error
ea.
In
a
qui
a

Explanation:

  • give() collects the words in a single list and returns them all
  • inside give(), a with statement is used to ensure the file is properly handled (closed at the end...)
  • for w in words browses all the words from the list
  • [letter not in forbid for letter in w] is a comprehension list that contains booleans only. For each letter of the current examined word (i.e. w), it will put True if the letter does not belong to forbid. all() is True only if all the booleans from the list are True, so only if all letters of w do not belong to forbid
  • the last part could be shortened

like this:

def enter(forbid):
    for w in give():
        if all([letter not in forbid for letter in w]):
            print w
Sign up to request clarification or add additional context in comments.

Comments

0

As already pointed out, the indentation is wrong, also give() does not return anything so words is assigned a NoneType.

3 Comments

Okay. Got it. Thanks
Actually the reason why give() does not return anything in the original code is not because of the wrong indentation (that should trigger a syntax error) but because give() has no return statement
@zezollo I tried to work that out. But unfortunately, it doesn't. I am trying to extract those words from the txt file that do not have those specific letters.
0

I've tried your code, but could not work anything out, so I took a program i wrote some time ago, as far as i can see, you open the file on the wrong way, here is my code:

fo = open('your_file_name.txt','rt')
for line in fo:
    print(line)

fo.close()

as you can see you did not add the 'rt' wich stands for reading and text mode, hope this helped.

Thanks

Comments

0

You have to return a value in give() function..

def give():
    fin=open('words2.txt', 'r')
    line=fin.readlines()
    words = []
    for line in fin:
        word=line.split(" ")
        for i in word:
            print i
            words.append(i)
    return words
def enter(forbid):
    words=give()
    for letter in words:
        if letter in forbid:
            return False
        else:
            print words
            return True

4 Comments

this still dont print anything
still doesnt, maybe its python 3 im using
@SumanKalyan this won't work as intended because you will only return the first word. You should "collect" all the words in any iterator, then return it completely
@Cid-EL the print statements show this is python2 code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.