I'm trying to print the top 10 lines of a file. single spaced. without spaces at the end
What can i change so that the output is single spaced instead of double spaced?
thanks
so far I've got:
with open('1.txt') as f:
i = 1
while i <= 10:
line = f.readline()
print line
i = i+1
f.close()
and i get an out put of:
1
2
3
4
5
6
7
8
9
10
easiest fix is to put a comma on the end of the print statement:
change
print line
to
print line,
You can simply use str.rstrip('\n') to do this. rstrip trims a trailing character, which in this case would be \n (newline character).
with open('1.txt') as f:
i = 1
while i <= 10:
line = f.readline().rstrip('\n')
print line
i = i+1
f.close()
Related
I have a macro that searches but does not find the “7” (If Right(pair, 2) = 7 Then). The thing is when I change the number to 11 or 12 etc. (any two digits) and the findXX in the code, it works fine. Does anyone know what’s occurring and what is the exact change I need to do.
Option Explicit
Sub DivideSomeStuff()
Dim pair As Range, accumulator As Range
Dim findSeven As Double
Dim remainder As Long
For Each pair In Range("B30, F30, J30")
If Right(pair, 2) = 7 Then
If pair.Offset(0, 2) <= 12 Then
remainder = 0
Else
remainder = pair.Offset(0, 2) Mod 10
End If
findSeven = (pair.Offset(0, 2) - remainder) / 10
For Each accumulator In Range("A36, D36, G36, J36, M36, A40, D40, G40, J40, M40")
If accumulator.Offset(-1, 0) = Val(Left(pair, InStr(pair, "-") - 1)) Then
accumulator.Value = accumulator.Value + remainder
End If
accumulator.Value = accumulator.Value + findSeven
Next accumulator
End If
Next pair
End Sub
Change it from ...
Right(pair, 2) = 7
... to ...
Right(pair, 1) = 7
You’re currently getting the 2 right values when 7 is a single character.
You may need to put quotes around the 7 too, see if works without them though.
I have one program downloaded from internet and need to get each digit printed out from a three digit number. For example:
Input: 123
Expected Output:
1
2
3
I have 598
Need to Get:
5
9
8
I try using this formula but the problem is when number is with decimal function failed:
FIRST_DIGIT = (number mod 1000) / 100
SECOND_DIGIT = (number mod 100) / 10
THIRD_DIGIT = (number mod 10)
Where number is the above example so here is calulation:
FIRST_DIGIT = (598 mod 1000) / 100 = 5,98 <== FAILED...i need to get 5 but my program shows 0 because i have decimal point
SECOND_DIGIT = (598 mod 100) / 10 = 9,8 <== FAILED...i need to get 9 but my program shows 0 because i have decimal point
THIRD_DIGIT = (598 mod 10) = 8 <== CORRECT...i get from program output number 8 and this digit is correct.
So my question is is there sample or more efficient code that get each digit from number without decimal point? I don't want to use round to round nearest number because sometime it fill failed if number is larger that .5.
Thanks
The simplest solution is to use integer division (\) instead of floating point division (/).
If you replace each one of your examples with the backslash (\) instead of forward slash (/) they will return integer values.
FIRST_DIGIT = (598 mod 1000) \ 100 = 5
SECOND_DIGIT = (598 mod 100) \ 10 = 9
THIRD_DIGIT = (598 mod 10) = 8
You don't have to do any fancy integer calculations as long as you pull it apart from a string:
INPUT X
X$ = STR$(X)
FOR Z = 1 TO LEN(X$)
PRINT MID$(X$, Z, 1)
NEXT
Then, for example, you could act upon each string element:
INPUT X
X$ = STR$(X)
FOR Z = 1 TO LEN(X$)
Q = VAL(MID$(X$, Z, 1))
N = N + 1
PRINT "Digit"; N; " equals"; Q
NEXT
Additionally, you could tear apart the string character by character:
INPUT X
X$ = STR$(X)
FOR Z = 1 TO LEN(X$)
SELECT CASE MID$(X$, Z, 1)
CASE " ", ".", "+", "-", "E", "D"
' special char
CASE ELSE
Q = VAL(MID$(X$, Z, 1))
N = N + 1
PRINT "Digit"; N; " equals"; Q
END SELECT
NEXT
I'm no expert in Basic but looks like you have to convert floating point number to Integer. A quick google search told me that you have to use Int(floating_point_number) to convert float to integer.
So
Int((number mod 100)/ 10)
should probably the one you are looking for.
And, finally, all string elements could be parsed:
INPUT X
X$ = STR$(X)
PRINT X$
FOR Z = 1 TO LEN(X$)
SELECT CASE MID$(X$, Z, 1)
CASE " "
' nul
CASE "E", "D"
Exponent = -1
CASE "."
Decimal = -1
CASE "+"
UnaryPlus = -1
CASE "-"
UnaryNegative = -1
CASE ELSE
Q = VAL(MID$(X$, Z, 1))
N = N + 1
PRINT "Digit"; N; " equals"; Q
END SELECT
NEXT
IF Exponent THEN PRINT "There was an exponent."
IF Decimal THEN PRINT "There was a decimal."
IF UnaryPlus THEN PRINT "There was a plus sign."
IF UnaryNegative THEN PRINT "There was a negative sign."
Im trying to take the first line from the text file and then print that line with some data next to it. Here is my code and what the text file looks like.
def main():
file = open("votes.txt")
lines = file.readlines()
votes = 0
count = 0
count_all = 0
line = lines[1]
for i in line:
if i == 'y':
count += 1
count_all += 1
votes += 1
elif i == 'a':
votes += 1
else:
count_all += 1
votes += 1
print(lines[0]+':', (count/count_all), end='')
main()
and this is what the text file looks like:
Aberdeenshire
yyynnnnynynyannnynynanynaanyna
Midlothian
nnnnynyynyanyaanynyanynnnanyna
Berwickshire
nnnnnnnnnnnnnnnnnnnnynnnnnynnnnny
When I run the program i get this output:
Aberdeenshire
: 0.38461538461538464
For now all I need is for the Aberdeenshire to be in the same line as :0.3846
Not sure what language this is - Python? (not familiar with that really)...
I suspect the lines[] strings each have a carriage return on the end, so perhaps doing a strip() on them would remove this, something like this:
print(lines[0].strip()+':', (count/count_all), end='')
I have a step where I need to check certain message. I used a multi-line parameter:
Then I see welcome message: 'Welcome to our site!
Some more text
Even more text'
Problem is that message should have spaces at the end of first and second lines (IDK why, but it should). And JBehave trims spaces from each line. So test fails.
How can I set it not to trim this parameter?
I've tried writing \n instead of actual line-breaks, but it wasn't replaced with line-breaks
Also tried adding {trim=false} in the beginning of parameter, but it reads it as part of the parameter.
Made some experiments with quotation marks (used ", ', none), it didn't help either...
I have tested that and it seems that JBehave actually truncates spaces at the end of the test:
When some step with multitline parameter:first line has 10 spaces at the end
Second line has 6 spaces at the end
Third line has no spaces at the end, but fourth line has 8 spaces
Fifth line has 3 spaces, and Sixth line has only 7 spaces
#When("some step with multitline parameter:$lines")
public void stepWithMultilneString(String s) {
String lines [] = s.split("\\r?\\n");
for(int i = 0; i < lines.length; i++) {
System.out.format("Line %d is: >>%s<<\n", i+1, lines[i]);
}
}
Line 1 is: >>first line has 10 spaces at the end <<
Line 2 is: >>Second line has 6 spaces at the end <<
Line 3 is: >>Third line has no spaces at the end, but fourth line has 8 spaces<<
Line 4 is: >> <<
Line 5 is: >>Fifth line has 3 spaces, and Sixth line has only 7 spaces<<
When some step with multitline parameter:first line has 10 spaces at the end
Second line has 6 spaces at the end
Third line has no spaces at the end, but fourth line has 8 spaces
Fifth line has 3 spaces, and Sixth line has only 7 spaces
I suggest a bypass - a step with delimiters ! at the beginning and end of the text:
When step with multitline parameter surrounded by !:!first line has 10 spaces at the end
Second line has 6 spaces at the end
Third line has no spaces at the end, but fourth line has 8 spaces
Fifth line has 3 spaces, and Sixth line has only 7 spaces
!
#When("step with multitline parameter surrounded by !:$string")
public void stepWithMultilneStringVersion2(String s) {
if( s.startsWith("!")) {
s = s.substring(1);
}
if( s.endsWith("!")) {
s = s.substring(0, s.length()-1);
}
String lines [] = s.split("\\r?\\n");
for(int i = 0; i < lines.length; i++) {
System.out.format("Line %d is: >>%s<<\n", i+1, lines[i]);
}
}
Line 1 is: >>first line has 10 spaces at the end <<
Line 2 is: >>Second line has 6 spaces at the end <<
Line 3 is: >>Third line has no spaces at the end, but fourth line has 8 spaces<<
Line 4 is: >> <<
Line 5 is: >>Fifth line has 3 spaces, and Sixth line has only 7 spaces <<
Line 6 is: >> <<
When step with multitline parameter surrounded by !:!first line has 10 spaces at the end
Second line has 6 spaces at the end
Third line has no spaces at the end, but fourth line has 8 spaces
Fifth line has 3 spaces, and Sixth line has only 7 spaces
!
So I'm currently trying to sort values from a file. I'm stuck on the finding the first attribute, and am not sure why. I'm new to regex and ruby so I'm not sure how to go about the problem. I'm trying to find values of a,b,c,d,e where they are all positive numbers.
Here's what the line will look like
length=<a> begin=(<b>,<c>) end=(<d>,<e>)
Here's what I'm using to find the values
current_line = file.gets
if current_line == nil then return end
while current_line = file.gets do
if line =~ /length=<(\d+)> begin=((\d+),(\d+)) end=((\d+),(\d+))/
length, begin_x, begin_y, end_x, end_y = $1, $2, $3, $4, $5
puts("length:" + length.to_s + " begin:" + begin_x.to_s + "," + begin_y.to_s + " end:" + end_x.to_s + "," + end_y.to_s)
end
end
for some reason it never prints anything out, so I'm assuming it never finds a match
Sample input
length=4 begin=(0,0) end=(3,0)
A line with 0-4 decimals after 2 integers seperated by commas.
So it could be any of these:
2 4 1.3434324,3.543243,4.525324
1 2
18 3.3213,9.3233,1.12231,2.5435
7 9 2.2,1.899990
0 3 2.323
Here is your regex:
r = /length=<(\d+)> begin=((\d+),(\d+)) end=((\d+),(\d+))/
str.scan(r)
#=> nil
First, we need to escape the parenthesis:
r = /length=<(\d+)> begin=\((\d+),(\d+)\) end=\((\d+),(\d+)\)/
Next, add the missing < and > after "begin" and "end".
r = /length=<(\d+)> begin=\(<(\d+)>,<(\d+)>\) end=\(<(\d+)>,<(\d+)>\)/
Now let's try it:
str = "length=<4779> begin=(<21>,<47>) end=(<356>,<17>)"
but first, let's set the mood
str.scan(r)
#=> [["4779", "21", "47", "356", "17"]]
Success!
Lastly (though probably not necessary), we might replace the single spaces with \s+, which permits one or more spaces:
r = /length=<(\d+)>\s+begin=\(<(\d+)>,<(\d+)>\)\send=\(<(\d+)>,<(\d+)>\)/
Addendum
The OP has asked how this would be modified if some of the numeric values were floats. I do not understand precisely what has been requested, but the following could be modified as required. I've assumed all the numbers are non-negative. I've also illustrated one way to "build" a regex, using Regexp#new.
s1 = '<(\d+(?:\.\d+)?)>' # note single parens
#=> "<(\\d+(?:\\.\\d+)?)>"
s2 = "=\\(#{s1},#{s1}\\)"
#=> "=\\(<(\\d+(?:\\.\\d+)?)>,<(\\d+(?:\\.\\d+)?)>\\)"
r = Regexp.new("length=#{s1} begin#{s2} end#{s2}")
#=> /length=<(\d+(?:\.\d+)?)> begin=\(<(\d+(?:\.\d+)?)>,<(\d+(?:\.\d+)?)>\) end=\(<(\d+(?:\.\d+)?)>,<(\d+(?:\.\d+)?)>\)/
str = "length=<47.79> begin=(<21>,<4.7>) end=(<0.356>,<17.999>)"
str.scan(r)
#=> [["47.79", "21", "4.7", "0.356", "17.999"]]
Sample input:
length=4 begin=(0,0) end=(3,0)
data.txt:
length=3 begin=(0,0) end=(3,0)
length=4 begin=(0,1) end=(0,5)
length=2 begin=(1,3) end=(1,5)
Try this:
require 'pp'
Line = Struct.new(
:length,
:begin_x,
:begin_y,
:end_x,
:end_y,
)
lines = []
IO.foreach('data.txt') do |line|
numbers = []
line.scan(/\d+/) do |match|
numbers << match.to_i
end
lines << Line.new(*numbers)
end
pp lines
puts lines[-1].begin_x
--output:--
[#<struct Line length=3, begin_x=0, begin_y=0, end_x=3, end_y=0>,
#<struct Line length=4, begin_x=0, begin_y=1, end_x=0, end_y=5>,
#<struct Line length=2, begin_x=1, begin_y=3, end_x=1, end_y=5>]
1
With this data.txt:
2 4 1.3434324,3.543243,4.525324
1 2
18 3.3213,9.3233,1.12231,2.5435
7 9 2.2,1.899990
0 3 2.323
Try this:
require 'pp'
data = []
IO.foreach('data.txt') do |line|
pieces = line.split
csv_numbers = pieces[-1]
next if not csv_numbers.index('.') #skip the case where there are no floats on a line
floats = csv_numbers.split(',')
data << floats.map(&:to_f)
end
pp data
--output:--
[[1.3434324, 3.543243, 4.525324],
[3.3213, 9.3233, 1.12231, 2.5435],
[2.2, 1.89999],
[2.323]]