I have 3 parts in my code. My first part tells me what line number the condition is on for line1. My second part tells me what line number the condition is on for line2. The last part makes the numbers as a range and prints out the range.
The first part of the code: I get a result of 6 for num1.
For the second part of the code I get 24 when i run it by itself but a 18 when i run it with part 1.
Then at the 3rd part i index the file and i try to get the proper lines to print out, but they dont work because my first part of my code is changing numbers when i have both conditions running at the same time.
Is there a better way to run this code with either just indexing or just enumerating? I need to have user input and be able to print out a range of of the file based off the input.
#Python3.7.x
#
#
import linecache
#report=input('Name of the file of Nmap Scan:\n')
#target_ip=input('Which target is the report needed on?:\n')
report = "ScanTest.txt"
target_ip = "10.10.100.2"
begins = "Nmap scan report for"
fhand = open(report,'r')
beginsend = "\n"
#first statement
for num1,line1 in enumerate(fhand, 1):
line1 = line1.rstrip()
if line1.startswith(begins) and line1.endswith(target_ip):
print(num1)
print(line1)
break
#second statement
for num2,line2 in enumerate(fhand, 1):
line2 = line2.rstrip()
if line2.startswith(beginsend) and num2 > num1:
print(num2)
print(line2)
break
with open('ScanTest.txt') as f:
linecount = sum(1 for line in f)
for i in range(num1,num2):
print(linecache.getline("ScanTest.txt", i))
The first part of the code: I get a result of 6 for num1. for the second part of the code I get 24 when i run it by itself but a 18 when i run it with part 1.
Obviously the second part continues reading the file where the first part stopped.
The minimal change is to put
num2 += num1
after the second loop, or just change the 3rd loop to for i in range(num1, num1+num2):. The condition and num2 > num1 within the second loop is to be removed.
Related
So I'm having trouble with enters and line breaks in my code. I must use easyinput library (and import read).
My code stands for:
Input: Input consists of several cases separated by an empty line. Every case has three parts ('lines'). The first one is a line with the translation table: 26 different characters (with no spaces nor ‘_’), the first one corresponding to ‘a’, the second one to ‘b’, …, and the last one to ‘z’. The second part is a number n > 0 in a line. The third part consists of n encrypted lines of text.
Output: For each case, write the original text, also with n lines. Change each ‘_’ of the encrypted text for a space. Write an empty line at the end of each case.
So I figured out how to solve the problem, the things is that my code prints 'well' entering line by line in input. But the problem input must be entered the whole entire. I put an example for better understanding:
Some input should be:
52-!813467/09*+.[();?`]<:>
6
5_3++!_305))_6*_;48_26)4+.)_4+);80_6*_;48_!8`60)_)85;
;]8*;:_+*8_!83(88)_5*!_;46(;88*_96*?;8)
*+(;485);_5*!_2:_*+(;4
956*_2(5*-4_)8`8*;4_0692_85);_)6!8
)4++;_1(+9_;48_081;_8:8_+1_;48_!85;4)_485!
5_288_06*8_1(+9_;48_;(88_;4(+?34_;48_)4+;_161;:_188;_+?;
bcdefghijklmnopqrstuvwxyza
3
cfxbsf_pg_cvht_jo_uif_bcpwf_dpef
j_ibwf_pomz_qspwfe_ju_dpssfdu
opu_usjfe_ju
And its output must be:
a good glass in the bishops hostel in the devils seat
twenty one degrees and thirteen minutes
northeast and by north
main branch seventh limb east side
shoot from the left eye of the deaths head
a bee line from the tree through the shot fifty feet out
beware of bugs in the above code
i have only proved it correct
not tried it
My code far now is:
from easyinput import read
abc = 'abcdefghijklmnopqrstuvwxyz'
values = [letter for letter in abc]
old_abc = read(str)
while old_abc is not None:
keys = [old_letter for old_letter in old_abc]
dict_abc = dict(zip(keys, values))
num_lines = read(int)
for i in range(num_lines):
line = read(str)
for j in line:
if j == '_':
print(' ', end = '')
else:
print(dict_abc[str(j)], end = '')
print('\n')
old_abc = read(str)
I do not find a way of making my code easier, I just want some help to finally print the desired output. Thanks
Can someone enlighten me how to do this?
Write a Python program that reads a series of lines one by one from the keyboard (ending by an empty line) and, at the end, outputs the number of times that the first line occurred. For example, if it reads
hello
world
We say hello
hello
Birkbeck
hello
it would output 3 since the first line ("hello") occurred three times.
You may assume that the user enters at least two non-empty lines before the empty line.
not sure if you want to separate word with spaces or with the newline character and if we count the first occurence.
This is a sample solution for spaces separation between words. This works for the example that you provided
freq_dict = {}
word = input().split()
for w in word:
if w not in freq_dict.keys():
freq_dict[w] = 0
else:
freq_dict[w] += 1
print(freq_dict[word[0]])
I have an assignment that has instructions as follows:
write a program that reads in 4 sets of 4 dashed lines and outputs the four binary symbols that each set of four lines represents.
input consists of 16 lines in total, consisting of any number of dashes and spaces.
the first four lines represents a symbol, the next four lines represents the next symbol and so on.
print out the four binary-encoded symbols represented by the 16 lines in total.
each binary symbol should be on its own line
This is based upon a previous program that I wrote where input is a single line of text consisting of any number of spaces and dashes. If there is an even number of dashes in the line, output 0. Otherwise, output 1.
This is the code for the above:
line = input()
num_dashes = line.count("-")
mod = num_dashes % 2
if mod == 0:
print("0")
else:
print("1")
Please may someone assist me?
Thank you.
The code you have for processing one line is fine, although you could replace the if...else with just:
print(mod)
Now to extend this to multiple lines, it might be better not to call print like that, but to collect the output in a variable, and only output that variable when all 16 lines have been processed. This way the output does not get mixed with the input from the console.
So for instance, it could happen like this:
output = []
for part in range(4): # loop 4 times
digits = ""
for line in range(4): # loop 4 times
line = input()
num_dashes = line.count("-")
mod = num_dashes % 2
digits += str(mod) # collect the digit
output.append(digits) # append 4 digits to a list
print("\n".join(output)) # print the list, separated by linebreaks
I know there are a couple of post about this question on S.O. but they have not helped me solve my problem. I am trying to use an accumulator to sum up the values in a text file. When there is a number on each line my code just prints each line that is in the file. When there is a blank space between I get an error message. I think it is a simple oversight but I am new to Python so I am not sure what I am doing wrong.
My code:
def main():
#Open a file named numbers.txt
numbers_file = open('numbers.txt','r')
#read the numbers on the file
number = numbers_file.readline()
while number != '':
#convert to integer
int_number = int(number)
#create accumulator
total = 0
#Accumulates a total number
total += int_number
#read the numbers on the file
number = numbers_file.readline()
#Print the data that was inside the file
print(total)
#Close the the numbers file
numbers_file.close()
#Call the main function
main()
Inputs in the text file:
100
200
300
400
500
Gives me error message:
ValueError: invalid literal for int() with base 10: '\n'
Inputs in the text file:
100
200
300
400
500
Prints:
100
200
300
400
500
You need to exclude empty lines because you can't convert them to an int(). One pythonic (EAFP) way to do this is to catch the exception and ignore (though this will silently ignore any non-number line):
with open('numbers.txt','r') as numbers_file:
total = 0
for line in numbers_file:
try:
total += int(line)
except ValueError:
pass
print(total)
Or you can explicitly test that you don't have an empty string after you .strip() all the whitespace (this would still error for a non-numeric line, e.g. 'hello'):
with open('numbers.txt','r') as numbers_file:
total = 0
for line in numbers_file:
if line.strip():
total += int(line)
print(total)
This second one can be written as a generator expression:
with open('numbers.txt','r') as numbers_file:
total = sum(int(line) for line in numbers_file if line.strip())
print(total)
You are assigning the value 0 to your accumulator each time you go through the loop, before you add the new value. This means you're adding the new value to 0 each time, which means you're just printing the new value.
If you move the line total = 0 to occur before the loop, then it should work as you were hoping.
If you want, you can clean this up a little:
numbers_file = open('numbers.txt','r')
total = 0
for number in numbers_file:
if number:
int_number = int(number)
total += int_number
print(total)
numbers_file.close()
would be a first pass. The check if number returns True if number contains a "truthy" value, which in this case would happen if you hit an empty line.
Hi you are missing to remove the 'new line symbol' which is \n.
To ensure you get only literals that can be converted to numbers you have to strip other characters.
With e.g.
a = '100\ntest'
print(a.isnumeric())
a = '103478'
print(a.isnumeric())
You can test if there is a character that prevents conversion to a number.
The regular expression package to manipulate string easily.
See this stack overflow threat.
import re
a = jkfads1000ki'
re.sub('\D','',a)
'1000'
See the Python docs on re.
Beginning
Line 2
Line 3
Line 4
Line 5
Line 6
End
Trying to pull off line 2 through line 6. Can't do it to save my soul.
a is the saved string I'm searching through.
b = re.findall(r'Beginning(.*?)End', a)
Doesn't give me a thing, just a blank b. I know it's because of the newlines but how do I go about detecting and moving on forward with the newlines. I've tried, not knowing exactly for sure how I'm suppose to use MULTILINE or DOTALL. Nothing changed.
How do I go about getting it to put lines 2 through 6 in b?
To add in this will occur multiple times through the same file that I need to perform this search and pull technique. I have no other easy way of doing this since the information in Lines 2-6 need to be looked through further to pull off data that will be put into a csv file. Since some of the data contains hours and some of the data doesn't contain hours, aka Unavailable, I need to be able to pull off and differentiate between the two occurrences.
string = """Beginning
Line 2
Line 3
Line 4
Line 5
Line 6
End
"""
lines = string.splitlines()
answer = []
flag = False
for line in lines:
line = line.strip()
if not line: continue
if line == "Beginning":
flag = True
continue
if line == "End": flag = False
if not flag: continue
answer.append(line)
Output:
In [209]: answer
Out[209]: ['Line 2', 'Line 3', 'Line 4', 'Line 5', 'Line 6']
You could make a function that takes a multi-line string, then a starting line, and an ending line.
def Function(string, starting_line, ending_line):
if "\n" in string: #Checks for whether or not string is mult-line
pass
else:
return "The string given isn't a multiline string!" #If string isn't multiline, then Function returns a string explaining that string isn't a multi-line string
if ending_line < starting_line: #Checks if ending_line < starting_line
return "ending_line is greater than starting_line!" #If ending_line < starting_line, then Function returns a string explaining that ending_line > starting_line
array = [] #Defines an array
for i in range(len(string)): #Loops through len(string)
if list(string)[i] = "\n": #Checks whether list(string)[i] = a new line
array.append(i) #Appends i to array
return string[array[starting_line - 1]::array[ending_line - 1]]
print(Function(a, 3, 7))
This code should return:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6