How to find specific index by its content - python

wordlist = open(r'C:\Users\islam\Desktop\10k most passwords.txt')
for words in wordlist:
line = (words.split())
for count, ele in enumerate(wordlist, 1):
x=(([count, ele]))
print(x)
The output :
[9994, 'hugohugo\n']
[9995, 'eighty\n']
[9996, 'epson\n']
[9997, 'evangeli\n']
[9998, 'eeeee1\n']
[9999, 'eyphed']
How could I find index 0 by typing its content , like input 9995 and the output be :
[9995, 'eighty\n']

This is one approach:
with open('path/to/file') as file:
data = file.readlines()
while True:
try:
user_input = int(input('Enter index:'))
if user_input < 1:
raise ValueError
print(data[user_input - 1].strip())
except (ValueError, IndexError):
print('Invalid index value')
I would say pretty simple since if You split by readlines it already is a list and can be accessed using indexes (subtract 1 to "start" index from 1), the rest of the code that includes error handling is for user convenience.
Simply for getting a value from a "hardcoded" index:
with open('path/to/file') as file:
data = file.readlines()
index = 5
print(data[index - 1])

you can try this:
list.index(element, start, end)
element - the element to be searched
start (optional) - start searching from this index
end (optional) - search the element up to this index
At the place of list you write your list name.
I think this may help

Related

Python find index of string with while loop

New to python-
I need to create a "while" loop that searches for the position of a certain string in a text file.
All the characters in the file have been set to integers (x = len(all)), so now I need a loop to search for the index/position of a certain string.
This is where I'm at right now:
string = 'found'
index = 0
while index < x:
if ????
Then it should print out something like
String found between (startIndex) and (endIndex)
You can use the .find() function:
string = "found"
x = "I found the index"
index = x.find(string)
end = index + len(string)
print(index, end)
2, 7
Python has a built-in function called index that provides this functionality:
string = "found"
with open("FILE", "r") as f:
for i,j in f.readlines():
if string in j:
foo = f.index(string)
print(f"String found at line {i+1} between ({foo}) and ({foo + len(string)})")
break

Can't access list using index

The following code shows that IndexError: list index out of range
Here i am trying to find a string which starts from "From" and then print the word next to it using .split()
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
for a in fh:
a=a.rstrip()
b=a.split()
if b[0]=="From":
count=count+1
print(b[1])
print("There were", count, "lines in the file with From as the first word")
for the following line
if b[0]=="From":
Where am i going wrong?
Validate the length before accessing the index of array.
if len(b) > 0 and b[0] == 'From':
Also make sure to close the file that is opened.
fh.close()
well the problem is if a is empty a.strip will return nothing so you need to check for if a != "" and you should be good

How to find check only first index in each split string?

I am trying to create define a function that:
Splits a string called text at every new line (ex text="1\n2\n\3)
Checks ONLY the first index in each of the individual split items to see if number is 0-9.
Return any index that has 0-9, it can be more than one line
ex: count_digit_leading_lines ("AAA\n1st") → 1 # 2nd line starts w/ digit 1
So far my code is looking like this but I can't figure out how to get it to only check the first index in each split string:
def count_digit_leading_lines(text):
for line in range(len(text.split('\n'))):
for index, line in enumerate(line):
if 0<=num<=9:
return index
It accepts the arguement text, it iterates over each individual line (new split strings,) I think it goes in to check only the first index but this is where I get lost...
The code should be as simple as :
text=text.strip() #strip all whitespace : for cases ending with '\n' or having two '\n' together
text=text.replace('\t','') #for cases with '\t' etc
s=text.split('\n') #Split each sentence (# '\n')
#s=[words.strip() for words in s] #can also use this instead of replace('\t')
for i,sentence in enumerate(s):
char=sentence[0] #get first char in each sentence
if char.isdigit(): #if 1st char is a digit (0-9)
return i
UPDATE:
Just noticed OP's comment on another answer stating you don't want to use enumerate in your code (though its good practice to use enumeration). So the for loop modified version without enumerate is :
for i in range(len(s)):
char=s[i][0] #get first char in each sentence
if char.isdigit(): #if 1st char is a digit (0-9)
return i
This should do it:
texts = ["1\n2\n\3", 'ABC\n123\n456\n555']
def _get_index_if_matching(text):
split_text = text.split('\n')
if split_text:
for line_index, line in enumerate(split_text):
try:
num = int(line[0])
if 0 < num < 9:
return line_index
except ValueError:
pass
for text in texts:
print(_get_index_if_matching(text))
It will return 0 and then 1
You could change out your return statement for a yield, making your function a generator. Then you could get the indexes one by one in a loop, or make them into a list. Here's a way you could do it:
def count_digit_leading_lines(text):
for index, line in enumerate(text.split('\n')):
try:
int(line[0])
yield index
except ValueError: pass
# Usage:
for index in count_digit_leading_lines(text):
print(index)
# Or to get a list
print(list(count_digit_leading_lines(text)))
Example:
In : list(count_digit_leading_lines('he\n1\nhto2\n9\ngaga'))
Out: [1, 3]

Returning found char and index in list - Python

I have the following code:
I am trying to compare each char in the userInputList with the Letters array, if found in the letters array i would like to return it along with its index number; so if a user was to type hello: it would check if 'h' exists in Letters which it does, return the value and also return the index of it which is 7.
At the moment my if function checks against the index and not the actual character so it will always return true.
Any help would be appreciated.
Letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o',
'p','q','r','s','t','u','v','w','x','y','z']
userInput = input("Please enter what you would like to deycrpt:")
userInputList = list(userInput)
for i in range(0,len(userInputList)):
print(userInputList[i])
if userInputList[i] in Letters:
print("true")
i+=1
Thanks.
This should work:
# Python 2 users add the following line:
from __future__ import print_function
for letter in userInputList:
print(letter, end=': ')
try:
print('found at index', Letters.index(letter))
except ValueError:
print('not found')
You can iterate directly over userInputList without using i.
The method index returns the index of the first found entry and raises an IndexError if the value is not in the list. So catch this error and print that the letter is not found. Finally, print(letter, end=': ') suppresses the newline at the end of the print an puts : there, which make the letter and the message from the next print appear on the same line.
x = ord(raw_input("Digit a key: ")) - 97
if x < 26:
print("found at %d" % x)
else:
print("Not found!")
First, some comments:
don't use i+=1, the "for i in range loop" is already doing this for you.
You can also use :
for i, item in enumerate(userInputList):
to return you the index in the user list in i and the character at that index in item
then your check is good, but it's gonna give you with the for loop I gave you :
if item in Letters:
print("{} is in position {}".format(item, i))
format function will replace the "{}" in the string by the values item and i ( in this order)
Is this what you are looking for ?

How to check if the next element in a text file is 1 more than the previous element?

I have a programming homework question:
What is a good method to create a script that checks if the next element in a text file is equal to the previous plus 1 and report back the line in the text file that fails to meet this condition?
The text file looks like:
1
3
2
4
What I have so far:
filename=input('filename')
easy_text_file = open(filename, "rU")
store=1
count=0
for entry in easy_text_file:
entry_without_newline = entry[:-1]
data_list=list(entry_without_newline)
if store != data_list[0]:
print(store)
print(data_list[0])
count=count+1
print('This line does not satisfy the condition at line: ',count)
break
store=data_list[0]
print(store)
count=count+1
If I edit the text file to be:
1
2
3
4
6
5
It still returns "This line does not satisfy the condition at line: 1"
It seems that, you just have to keep track on two consecutive lines and check the condition for pair of lines -> 1-2 2-3 3-4 4-5 ...
This code works fine, I am just reading a line and keeping the track of previous line.
x=True
count=0
f=open("text.txt")
for line in f:
if (x==True): #This condition will be true just once.(for first line only)
prevline=line
line = f.next() #reading the second line. I will save this line as previous line.
x=False
a=int(prevline) #typecasting
b=int(line)
a=a+1
if(a!=b):
print "this line does not satisfy the condition at line:",count
prevline=line #keeping the track of previous line
count=count+1
f.close()
Read the first line of the file before entering the loop. This will allow you to initialise the expected sequence without assuming that the first number in the file is 1.
Once initialised, just keep track of the value that you expect on the next line, read a line from the file, convert it to an integer, compare it to the expected value, and print an error message if the values do not agree.
You don't need to convert each line to a list, just use int() - which also ignores new line characters. You should also handle non-numeric data - int() will raise ValueError if it can't convert the line to a valid integer.
Also, you can keep track of line numbers using a counter (as per your code), or by using enumerate().
Putting all of that together you might code it like this:
filename = input('filename')
with open(filename, 'rU') as easy_text_file:
expected = int(next(easy_text_file)) + 1 # initialise next line from first line
for line_number, entry in enumerate(easy_text_file, 2):
try:
entry = int(entry)
if entry != expected:
print("Line number {} does not satisfy the condition: expected {}, got {!r}".format(line_number, expected, entry))
expected = entry + 1
except ValueError:
print("Line number {} does not contain a valid integer: {!r}".format(line_number, entry)
Build a generator to return each line as an int
Read the first line, and build a counter that yields the expected values
Compare each value and expected value
Where they differ, print the line number, the value and expected value and break
Where a break didn't occur (the else associated with the for) - print all good
Eg:
from itertools import count
with open('testing.txt') as fin:
lineno = 0
lines = map(int, fin)
try:
expected = count(next(lines) + 1)
for lineno, (fst, snd) in enumerate(zip(lines, expected), 2):
if fst != snd:
print('problem on line {}: got {}, expected {}'.format(lineno, fst, snd))
break
else:
print('All was fine')
except StopIteration:
print('File was empty')
except ValueError as e:
print('Error converting line {} - {}'.format(lineno + 1, e))
Another alternative :
easy_text_file = open("number.txt", "rU")
#directly iterate each line of easy_text_file, convert it to int and create list
initial = [int(line) for line in easy_text_file]
#Based your requirement : next value should be equal to previous + 1
#So we create list with starting point from first value to length of initial list
compare = range(initial[0], len(initial)+1)
#Using zip function to create a match tuple between those list
#Output of zip(initial, compare) => [(1,1),(2,2),(3,3),(5,4), ....]
#Then we compare between each values
for i, j in zip(initial, compare):
if i!=j:
print 'This line does not satisfy the condition at line: ', j
break
easy_text_file.close()
result :
>>>
This line does not satisfy the condition at line: 4
>>> initial
[1, 2, 3, 5, 5, 3, 5]
>>> compare
[1, 2, 3, 4, 5, 6, 7]
>>>

Categories

Resources