Member Avatar

i have this code but this only prints the line number in the incorrect word *text1*. however i want it to print the line number of the incorrect word located in the text file called words. what can i add to it or arrange?
# text1 is my incorrectwords
# words is my txt file

from collections import defaultdict
d = defaultdict(list)
for lineno, word in enumerate(text1):

Recommended Answers

All 3 Replies

I'm not exactly sure what you're trying to say but I'll try to help you. From what I understand, you want to search through a text file for a certain word denoted by the variable 'text1' and print the line number in which it is found?

If so, try this:


text1 = "the" # Change to whatever you would like
lineNumber = 0

f = open("words.txt", "r")
for line in f.readlines():
    lineNumber += 1
    if text1 in line:
        print "Word found at line", lineNumber

I would prefer to formulate the SoulMazer's code like this

text1 = "user" # Change to whatever you would like

f = open("D:/Python26/LICENSE.txt", "r")
for lineno,line in enumerate(f.readlines()):
    if text1 in line.lower():
        print "Word found at line", lineno+1
Member Avatar

this is my full code now the code you showed me isnt what i want i need to print the incorrect word which i already have as a list and the line umber of that incorrect word located in the txt file
however i dont want to open the txt file since i already have it as a list and the incorrect words as a list
so this prints words in the txt file and the line number
but i want it to print the line number of the incorrect words in my list words[]

import sys
import string

text = []
infile = open(sys.argv[1], 'r').read()
for punct in string.punctuation:
    infile = infile.replace(punct, "")
    text = infile.split()
dict = open(sys.argv[2], 'r').read()
dictset = []
dictset = dict.split()
words = []
words = list(set(text) - set(dictset))
words = [text.lower() for text in words]

from collections import defaultdict
text = set()
with open("soccer.txt", "rt") as f:
    for word in f.readlines():
words = defaultdict(list)
with open("soccer.txt", "rt") as f:
    for line_no, line in enumerate(f):
        for word in line.split():
            if word not in text:
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.