Get filename from user and convert the number into list - python-3.x

So far, I have this:
def main():
bad_filename = True
l =[]
while bad_filename == True:
try:
filename = input("Enter the filename: ")
fp = open(filename, "r")
for f_line in fp:
a=(f_line)
b=(f_line.strip('\n'))
l.append(b)
print (l)
bad_filename = False
except IOError:
print("Error: The file was not found: ", filename)
main()
this is my program and when i print this what i get
['1,2,3,4,5']
['1,2,3,4,5', '6,7,8,9,0']
['1,2,3,4,5', '6,7,8,9,0', '1.10,2.20,3.30,0.10,0.30']
but instead i need to get
[1,2,3,4,5]
[6,7,8,9,0.00]
[1.10,2.20,3.3.0,0.10,0.30]

Each line of the file is a series on numbers separated by commas, but to python they are just characters. You need one more conversion step to get your string into a list. First split on commas to create a list of strings each of which is a number. Then use what is called "list comprehension" (or a for loop) to convert each string into a number:
b = f_line.strip('\n').split(',')
c = [float(v) for v in b]
l.append(c)
If you really want to reset the list each time through the loop (your desired output shows only the last line) then instead of appending, just assign the numerical list to l:
b = f_line.strip('\n').split(',')
l = [float(v) for v in b]
List comprehension is a shorthand way of saying:
l = []
for v in b:
l.append(float(v))
You don't need a or the extra parentheses around the assignment of a and b.

Related

How to extract only the digits and print as a string

Here I want to extract 011700 (these are 6 digit codes) which I want to extract without the semi-colon and later I will use a dict for a value against it.
How do I extract only 011700 (or 6 digit number from that line)?
And how to print it as a 6 digit number - instead of printing it like ['011700']?
Thanks.
import re
line = "N 011700; 3;20:34:00:02:ac:07:e9:d5;2f:f7:00:02:ac:07:e9:d5; 3333"
line_list = line.split()
print(line_list)
result = (re.findall('\\d+', line))
print(result)
Here's how I would go about modifying your current code.
First, I would specify that you are trying to split the string by semicolons, by changing your split line to:
line_list = line.split(";")
Then I would trim off any whitespace, which you could do with a second line like:
line_list = [l.strip() for l in line_list]
(or by combining them like)
line_list = [l.strip() for l in line.split(";")]
Then I would simply loop through the list like so:
for l in line_list:
if len(l) == 6:
result = l
break
And if you want the result to be the actual number and not just a string of the number, change the line to:
result = int(l)
Altogether that would look like this:
line = "N 011700; 3;20:34:00:02:ac:07:e9:d5;2f:f7:00:02:ac:07:e9:d5; 3333"
line_list = [l.strip() for l in line.split(";")]
for l in line_list:
if len(l) == 6:
result = int(l)
break
print(line_list)
print(result)
Result now contains the string of the first six-digit number found in your original string.

Remove Punctuation from Strings in File

So I have having trouble making a tuples list in ascending order that removes special characters. So far, I am able to strip to each character and gain a count as well as printing in ascending order. However I have been unsuccessful in removing special characters from the strings and they are included in my count. I understand I need to use the .translate method and include string.punctuation, but I haven't been able to place it in the right area. Here is my code.
import string
def Tuplelist():
fname = input('Please enter file name to process: ')
try:
fopen = open(fname)
except:
print('file name', fname, "doesn't exist.")
return
counts = {}
for line in fopen:
words = line.strip('\n')
word2 = words.lower()
wordy = word2.split()
for word in wordy:
for letter in word:
counts[letter] = counts.get(letter,0) + 1
listletter = []
for key, val in counts.items():
listletter.append((key, val))
print( sorted ( [ (v,k) for k,v in counts.items() ] ) )
I am still unable to convert the special characters by inserting string.punctuation as it states "'dict object has no attribute "translate"".

Nested for loop in python doesn't iterate fully

I have the following code to replace just one set of value from 26th line of 150 lines data. The problem is with the nested for loop. From the second iteration onwards, the inner loop isn't executing. Instead the loop skips to the last line
n= int(input("Enter the Number of values: "))
arr = []
print ('Enter the Fz values (in Newton): ')
for _ in range(n):
x=(input())
arr.append(x)
print ('Array: ', arr)
os.chdir ("D:\Work\python")
f = open("datanew.INP", "r+")
f1 = open("data.INP", "w+")
for i in range(len(arr)):
str2 = arr[i]
for j,line in enumerate(f):
if j == 25 :
new = line.split()
linenew = line.replace(new[1],str2)
print (linenew)
f1.write(linenew)
else:
f1.write(line)
print(arr[i], 'is replaced')
f.close()
f1.close()
The issue is that your code is looping over a file. On the first pass through, the end of file is reached. After that, there is no data left in the file to read, so the next loop has nothing to iterate over.
Instead, you might try reading over the whole file and storing the data in a list, then looping over that list. (Alternatively, you could eliminate the loops and access the 26th item directly.)
Here is some simple code to read from one file, replace the 26th line, and write to another file:
f = open("data.INP", "r") # Note that for simple reading you don't need the '+' added to the 'r'
the_data = f.readlines()
f.close()
the_data[25] = 'new data\n' # Remember that Python uses 0 indexing, thus the 25
f1 = open("updated_data.out", "w") # Assuming you want to write a new file, leave off the '+' here, as that indicates that you want to append to an existing file
for l in the_data:
f1.write(l)
f1.close()

python function call not printing as expected

So I have 2 functions - displayHand(hand) and calculateHandlen(hand)
def displayHand(hand):
"""
Displays the letters currently in the hand.
For example:
>>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
for letter in hand.keys():
for j in range(hand[letter]):
print(letter,end=" ")
print()
def calculateHandlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string-> int)
returns: integer
"""
handLen = 0
for i in hand:
handLen = handLen + hand.get(i,0)
return handLen
There's a loop in another function that is dependent on the above functions -
def playHand(hand, wordList, n):
"""
hand = dictionary
wordList = list of valid words
n = an integer passed while function call
"""
totalscore = 0
while(calculateHandlen(hand)>0):
print("Current Hand: " +str(displayHand(hand)))
newWord = input('Enter word, or a "." to indicate that you are finished: ')
Function call for playHand() is as follows:
wordList = loadWords() #loadWords could be a list of words
playHand({'n':1, 'e':1, 't':1, 'a':1, 'r':1, 'i':2}, wordList, 7)
I'm expecting the output to be:
Current Hand: n e t a r i i
Enter word, or a "." to indicate that you are finished:
However, it displays the following:
n e t a r i i
Current Hand: None
Enter word, or a "." to indicate that you are finished:
Don't know where I'm going wrong.
Note: I'm not allowed to make any changes to the first 2 functions.
displayHand() doesn't return anything, so the default None is returned. When you call it, it prints the output directly.
If you are not allowed to alter displayHand(), you need to print your label first, then call the function:
print("Current Hand: ", end='')
displayHand(hand)
The end='' removes the newline print() would normally write.

How to print 1st string of file's line during second iteration in python

Actually My file contents are.
ttsighser66
dagadfgadgadgfadg
dafgad
fgadfgad
ttsighser63
sadfsadf
asfdas
My code
file=open("C:\\file.txt","r")
cont = []
for i in file:
dd = i.strip("\n")
cont.append(dd)
cc = ",".join(cont)
if "tt" in i:
cc = ",".join(cont[:-1])
print(cont[-1], cc)
cont = []
My code generate below Output:
ttsighser66
ttsighser63 dagadfgadgadgfadg,dafgad,fgadfgad
But I want output like below format
ttsighser66,dagadfgadgadgfadg,dafgad,fgadfgad
ttsighser63,sadfsadf,asfdas
file=open("file.txt","r")
cont = []
for i in file:
dd = i.strip("\n")
cont.append(dd)
#print('cc',cont)
if "ttsighser" in i and len(cont) != 1:
cc = ",".join(cont[:-1])
print(cc)
cont = []
cont.append(dd)
print(",".join(cont))
If you don't need to store any strings to a list and just need to print strings, you could try this instead.
with open("file.txt", "r") as f:
line_counter = 0
file_lines = f.readlines()
for i in file_lines:
dd = i.strip()
if "tt" in dd:
print("{0}{1}".format("\n" if line_counter > 0 else "", dd), end="")
else:
print(",{0}".format(dd), end="")
line_counter += 1
print("")
The reason why your code displays
ttsighser66
ttsighser63 dagadfgadgadgfadg,dafgad,fgadfgad
instead of
ttsighser66,dagadfgadgadgfadg,dafgad,fgadfgad
ttsighser63,sadfsadf,asfdas
is because when you first encounter 'ttsighser66', it is appended to cont. Then since 'ttsighser66' contains 'tt', we would proceed to the conditional branch.
In the conditional branch, we would be joining the first and second to the last string in cont in cc = ",".join(cont[:-1]). However, since we only have 'ttsighser66' in cont, cont[:-1] will give us [] (an empty list). Since cont[:-1] is empty, ",".join(cont[:-1]) will be empty as well. Thus, cc will be empty. Since cc is empty, print(cont[-1], cc) will give us ttsighser66.
In the second line, ttsighser63 dagadfgadgadgfadg,dafgad,fgadfgad gets displayed because cont contains more than one value already so it will also display the values before 'ttsighser63'.
The remaining strings are not displayed because, based from your code, it would need another string containing 'tt' before the strings in cc could be displayed.
Essentially, you require a pair of strings containing 'tt' to display the strings between the pairs.
Additonal remark: The line cc = ",".join(cont) in your code seems pretty useless since its scope is limited to the for loop only and its value is being replaced inside the conditional branch.
version 1 (all data in list of strings && 1 time print)
fp=open("file.txt", "r")
data = []
for line in fp:
if "tt" in line:
data.append(line.strip())
else:
data.append(data.pop() + "," + line.strip())
fp.close()
[print (data) for line in data]
Version 2 (all data in a single string && 1 time print)
fp=open("file.txt","r")
data = ""
for line in fp:
if "tt" in line:
data += "\n" + line.strip()
else:
data += ","+line.strip()
fp.close()
data = data[1:]
print (data)

Resources