Python: Search particular string in file - python

I have text file, that store orders info in following format. I try to search an order by first line of the block, that represent ID and print 7 next lines. But my code checking just the first line or print all line's that contain an input number. Could somebody help me?
4735
['Total price: ', 1425.0]
['Type of menu: ', 'BBQ']
['Type of service: ', ' ']
['Amount of customers: ', 25.0]
['Discount: ', '5%', '= RM', 75.0]
['Time: ', '2017-01-08 21:39:19']
3647
['Total price: ', 2000.0]
['Type of menu: ', ' ']
['Type of service: ', 'Tent ']
['Amount of customers: ', 0]
.......
I use the following code to search in text file.
try:
f = open('Bills.txt', 'r')
f.close()
except IOError:
absent_input = (raw_input("|----File was not founded----|\n|----Press 'Enter' to continue...----|\n"))
report_module = ReportModule()
report_module.show_report()
Id_input = (raw_input("Enter ID of order\n"))
with open("Bills.txt", "r") as f:
searchlines = f.readlines()
j = len(searchlines) - 1
for i, line in enumerate(searchlines):
if Id_input in str(line): # I also try to check in this way (Id_input == str(line)), but it didn't work
k = min(i + 7, j)
for l in searchlines[i:k]: print l,
print
else:
absent_input = (raw_input("|----Order was not founded----|\n|----Press 'Enter' to continue...----|\n"))
report_module = ReportModule()
report_module.show_report()

check the following code.
Id_input = (raw_input("Enter ID of order\n")).strip()
try:
f = open("Bills.txt", "r")
print_rows = False
for idline in f:
if idline.strip() == Id_input:
print_rows = True
continue
if print_rows:
if idline.startswith("["):
print idline
else:
break
if not print_rows:
absent_input = (raw_input("|----Order was not founded----|\n|---- Press 'Enter' to continue...----|\n"))
report_module = ReportModule()
report_module.show_report()
except IOError:
absent_input = (raw_input("|----File was not founded----|\n|---- Press 'Enter' to continue...----|\n"))
report_module = ReportModule()
report_module.show_report()

Related

Line split is not functioning as intended

I am trying to get this code to split one at a time, but it is not functioning as expected:
for line in text_line:
one_line = line.split(' ',1)
if len(one_line) > 1:
acro = one_line[0].strip()
meaning = one_line[1].strip()
if acro in acronyms_dict:
acronyms_dict[acro] = acronyms_dict[acro] + ', ' + meaning
else:
acronyms_dict[acro] = meaning
Remove the ' ' from the str.split. The file is using tabs to delimit the acronyms:
import requests
data_site = requests.get(
"https://raw.githubusercontent.com/priscian/nlp/master/OpenNLP/models/coref/acronyms.txt"
)
text_line = data_site.text.split("\n")
acronyms_dict = {}
for line in text_line:
one_line = line.split(maxsplit=1) # <-- remove the ' '
if len(one_line) > 1:
acro = one_line[0].strip()
meaning = one_line[1].strip()
if acro in acronyms_dict:
acronyms_dict[acro] = acronyms_dict[acro] + ", " + meaning
else:
acronyms_dict[acro] = meaning
print(acronyms_dict)
Prints:
{
'24KHGE': '24 Karat Heavy Gold Electroplate',
'2B1Q': '2 Binary 1 Quaternary',
'2D': '2-Dimensional',
...

Create variables from text file in Python

This is linked to this question here I used the first answer, I tried changing the code but it didn't seem to work as that example has "[]" in the variables
I have a text file here:
room1North = CP
room1East = CP
room1South = OP
room1West = OP
room2North = OP
room2East = CP
room2South = EP
room2West = OP
I would like Python to create variables with the values in the text file so the variable "room1North = CP" in Python
I have the following code so far
with open("maze files.txt", "r") as f:
data = f.readlines()
room1North, room1East, room1South, room1West, room2North, room2Eeast, room2South, room2West = [d.split('=')[1].split('\n')[0] for d in data]
I get the following error:
IndexError: list index out of range
You don't actually want separate variables; you want a single dict whose keys are read from the file.
with open("maze files.txt", "r") as f:
data = {k:v for k, v in [line.strip().replace(' ', '').split("=") for line in f]}
# data["room1North"] == "CP"
# data["room1East"] == "CP"
# data["room1South"] == "OP"
# etc
Change your code as bellow
with open("maze files.txt", "r") as f:
data = f.readlines()
room1North, room1East, room1South, room1West, room2North, room2Eeast, room2South, room2West = [d.split('=')[1].split('\n')[0] for d in ''.join(data).split('\n')]
I think you'd have more luck using a dictionary rather than relying on pure variables.
with open("maze files.txt", "r") as f:
data = f.readlines()
rooms = {}
for i in data:
currentRoom = i.replace(' ', '').strip().split('=')
rooms[currentRoom[0]] = currentRoom[1]
What you'll be left with is a dictionary like the following
print(rooms)
#{'room1North ': ' CP', 'room1East ': ' CP', 'room1South ': ' OP', 'room1West ': ' OP', 'room2North ': ' OP', 'room2East ': ' CP', 'room2South ': ' EP', 'room2 West ': ' OP'}
You can reference each room and it's value by rooms["room1North"]

How would I overwrite the fav_genre of the user in this code

So I'm developing a code for a very basic music app, Every users information is saved into the database using the following format:
usrFile_write.write(username + ' : ' + password + ' : ' + name + ' : ' + dob + ' : ' + fav_artist + ' : ' + fav_genre + ' : ' + '\n' )
now I want to read the existing information of a particular user and allow them to change their fav_genre. Below is my failed attempt to do so:
textfile = 'user_DB.txt'
def a():
username = input('name?: ')
with open(textfile, 'r+') as textIn:
for line in textIn:
information = line.split(" : ")
if information[0] == username:
print('Your current genre is:',information[5])
new_genre = input('what would you like your new genre to be?')
information[5] = new_genre
textIn.write(information[5]=new_genre)#this line
print('new genre is saved to',information[5])
break
elif information != username:
print('Name not found, Please try again')
a()
else:print('invalid')
break
textIn.close()
a()
The line with the comment #this line is where I think the error is occouring as I want to overwrite the previous value of fav_genre for that specific user with the new one.Any ideas on what I could do different to make this work?
Basically change that line to:
textfile.write(' : '.join(information.values()) + '\n' )
So full code:
textfile = 'user_DB.txt'
updated_textfile = 'user_DB_Updated.txt'
def a():
username = input('name?: ')
updated_lines = []
with open(textfile, 'r+') as textIn:
for line in textIn:
information = line.split(" : ")
updated_lines.append(line)
if information[0] == username:
print('Your current genre is:',information[5])
new_genre = input('what would you like your new genre to be?')
information[5] = new_genre
updated_lines[-1] = ' : '.join(information) + '\n'
print('new genre is saved to ',information[5])
break
elif information != username:
print('Name not found, Please try again')
a()
else:print('invalid')
break
with open(updated_textfile, 'w+') as out_text:
out_text.write(''.join(updated_lines))
textfile.close()
a()

A more Pythonic way to display a header in the terminal

I've written a program to read in data files and do a bunch of nonsense with them that is irrelevant to this question. It will automatically skip the header when reading after the user inputs how many lines the header occupies.
I have built in some functionality to display the header in the terminal, if requested. Here is the functional yet idiotic looking snippet of code I've used to do this:
filename = (raw_input("Which file are we loading? "))
with open(filename) as myfile:
head = 'head'
aline = myfile.readline()
bline = myfile.readline()
cline = myfile.readline()
dline = myfile.readline()
eline = myfile.readline()
fline = myfile.readline()
gline = myfile.readline()
hline = myfile.readline()
iline = myfile.readline()
jline = myfile.readline()
kline = myfile.readline()
lline = myfile.readline()
mline = myfile.readline()
nline = myfile.readline()
oline = myfile.readline()
pline = myfile.readline()
qline = myfile.readline()
rline = myfile.readline()
sline = myfile.readline()
tline = myfile.readline()
header = input("How many header lines? (Type ``head`` to see the first 20 lines) ")
if header == head:
print ' 1 | ' + aline,
print ' 2 | ' + bline,
print ' 3 | ' + cline,
print ' 4 | ' + dline,
print ' 5 | ' + eline,
print ' 6 | ' + fline,
print ' 7 | ' + gline,
print ' 8 | ' + hline,
print ' 9 | ' + iline,
print '10 | ' + jline,
print '11 | ' + kline,
print '12 | ' + lline,
print '13 | ' + mline,
print '14 | ' + nline,
print '15 | ' + oline,
print '16 | ' + pline,
print '17 | ' + qline,
print '18 | ' + rline,
print '19 | ' + sline,
print '20 | ' + tline,
header = input("How many header lines? ")
Which appropriately gives:
How many header lines? (Type ``head`` to see the first 20 lines) head
1 | ------------------------------------------------------------------------------------------------------------------------------------------------
2 | K-KIDS GOLD LIST
3 | ------------------------------------------------------------------------------------------------------------------------------------------------
4 |
5 | N = 1048 K dwarfs within 50 parsecs
6 |
...
...
...
20 | stuff
Is there a more efficient and "Pythonic" way to go about this? Or is mine as good as it's going to get?
Cheers!
Not sure on the head and header logic but you can use itertools.islice to pull the first header_length lines and str.join to join the output:
from itertools import islice
filename = raw_input("Which file are we loading? "))
# ask user how many header lines
header_length = int(raw_input("Enter amount of header lines"))
with open(filename) as myfile:
# get the first header_length lines in a list
head = list(islice(myfile, header_length))
header = raw_input("How many header lines? (Type ``head`` to see the header lines)")
# if user types head
if "head" == header:
# use enumerate to get the line numbers/index in list
# the str.join the lines formatting index | line
print("".join(["{} | {}".format(i, line) for i, line in enumerate(head,start=1)]))
I believe that this is the functionality you're looking for:
filename = (raw_input("Which file are we loading? "))
with open(filename) as myfile:
file_lines = myfile.readlines() # save all lines from file into memory
header = raw_input("How many header lines? (Type ``head`` to see the first 20 lines) ")
num_to_print = 20 if header == 'head' else int(header) # get number of lines to be read. if 'head' then 20
for i, line in enumerate(file_lines[:num_to_print]):
print("{:02}|{}".format(i, line))

remove similar lines in text file

I am not using Python but I have script in python:
part of script
elif line.find("CONECT") > -1:
con = line.split()
line_value = line_value + 1
#print line_value
#print con[2]
try:
line_j = "e" + ', ' + str(line_value) + ', ' + con[2] + "\n"
output_file.write(line_j)
print(line_j)
line_i = "e" + ', ' + str(line_value) + ', ' + con[3] + "\n"
output_file.write(line_i)
print(line_i)
line_k = "e"+ ', ' + str(line_value) + ', ' + con[4] + "\n"
print(line_k)
output_file.write(line_k)
except IndexError:
continue
which give .txt output in format
e, 1, 2
e, 1, 3
e, 1, 4
e, 2, 1
e, 2, 3
etc.
I need remove similar lines with the same numbers, but no matter on order this numbers
i.e. line e, 2, 1..
Is it possible?
Of course, it is better to modify your code to remove that lines BEFORE you're writing them to file. You can use a list to store already saved values, and on each itereation, perfom a search if the values you're want to add is already exists in that list. The code below isn't tested and optimized, but it explains an idea:
# 'added = []' should be placed somewhere before 'if'
added = []
# you part of code
elif line.find("CONECT") > -1:
con = line.split()
line_value = line_value + 1
try:
line_j = "e, %s, %s\n" % (str(line_value),con[2])
tmp = sorted((str(line_value),con[2]))
if tmp not in added:
added.append(tmp)
output_file.write(line_j)
print(line_j)
line_i = "e, %s, %s\n" % (str(line_value),con[3])
tmp = sorted((str(line_value),con[3]))
if tmp not in added:
added.append(tmp)
output_file.write(line_i)
print(line_i)
line_k = "e, %s, %s\n" % (str(line_value),con[4])
tmp = sorted((str(line_value),con[4]))
if tmp not in added:
added.append(tmp)
print(line_k)
output_file.write(line_k)
except IndexError:
continue
Here is a comparison method for two lines of your file:
def compare(line1, line2):
els1 = line1.strip().split(', ')
els2 = line2.strip().split(', ')
return Counter(els1) == Counter(els2)
See the documentation for the Counter class.
If the count of elements doesn't matter you can replace the Counter class with set instead
The following approach should work. First add the following line further up in your code:
seen = set()
Then replace everything inside the try with the following code:
for con_value in con[2:5]:
entry = frozenset((line_value, con_value))
if entry not in seen:
seen.append(entry)
line_j = "e" + ', ' + str(line_value) + ', ' + con_value + "\n"
output_file.write(line_j)
print(line_j)
Make sure this code is indented to the same level as the code it replaces.

Categories