how to not remove space in file - python-2.7

how to keep the space betwen the words?
in the code it deletes them and prints them in column.. so how to print them in row and with the space?
s ='[]'
f = open('q4.txt', "r")
for line in f:
for word in line:
b = word.strip()
c = list(b)
for j in b:
if ord(j) == 32:
print ord(33)
if ord(j) == 97:
print ord(123)
if ord(j) == 65:
print ord(91)
chr_nums = chr(ord(j) - 1)
print chr_nums
f.close()

Short answer: remove the word.strip() command - that's deleting the space. Then put a comma after the print operation to prevent a newline: print chr_nums,
There are several problems with your code aside from what you ask about here:
ord() takes a string (character) not an int, so ord(33) will fail.
for word in line: will be iterating over characters, not words, so word will be a single character and for j in b is unnecessary.

Take a look at the first for loop :
for line in f:
here the variable named 'line' is actually a line from the text file you are reading. So this 'line' variable is actually a string. Now take a look at the second for loop :
for word in line:
Here you are using a for loop on a string variable named as 'line' which we have got from the previous loop. So in the variable named 'word' you are not going to get a word, but single characters one by one. Let me demonstrate this using a simple example :
for word in "how are you?":
print(word)
The output of this code will be as follows :
h
o
w
a
r
e
y
o
u
?
You are getting individual characters from the line and so you don't need to use another for loop like you did 'for j in b:'. I hope this helped you.

Related

access char without indexing in python

lines = []
while True:
line = raw_input()
if line:
lines.append(line)
else:
break
print lines
This would take line by line in a list. Output is:
In [27]: lines
Out[27]: ['x-xx', 'y->y', '-z->']
How do I access the next letter, currently being at a letter, in the following specified code:
count = 0 # to check how many '->' are there in each line
for sentence in lines:
for letter in sentence:
if letter == '-':
#check if the next character is '>' (How to code this line)
#and if so, increment count
else:
break
Is there a way out for this kind of for loop, where you don't index letter but iterate on letter itself directly?

What is the error in my python code

You are given an integer NN on one line. The next line contains NN space separated integers. Create a tuple of those NN integers. Let's call it TT.
Compute hash(T) and print it.
Note: Here, hash() is one of the functions in the __builtins__ module.
Input Format
The first line contains NN. The next line contains NN space separated integers.
Output Format
Print the computed value.
Sample Input
2
1 2
Sample Output
3713081631934410656
My code
a=int(raw_input())
b=()
i=0
for i in range (0,a):
x=int(raw_input())
c = b + (x,)
i=i+1
hash(b)
Error:
invalid literal for int() with base 10: '1 2'
There are three errors that I can spot:
First, your for-loop is not indented.
Second, you should not be adding 1 to i - the for-loop does this automatically.
Thirds - and this is where the error is thrown - is that raw_input reads the entire line. If you are reading the line '1 2', you cannot convert this to an int.
To fix this problem, I suggest doing:
line = tuple(map(int,raw_input().split(' ')))
This takes the raw input, splits it into an list, makes this list into ints, then turns this list into a tuple.
In fact, you can scrap the entire for loop. You could answer this problem in two lines of code:
raw_input()#To get rid of the first line, which we do not need
print hash(tuple(map(int,raw_input().split(' '))))
The input format
next line contains NN space separated integers
eg: 1 2 3, is not an integer (because of the spaces), that is why when you try int(raw_input()) your code throws an error. You should use split(' ') as the other answer has suggested, to separate each integer. This will remove the error.
Also, there is no need to use i=i+1 as the loop will take care of it
Try the below code:
if __name__ == '__main__':
n = int(input())
integer_list = map(int, input().split())
t = tuple(integer_list)
print(hash(t))
Try This code for Python-3
if __name__ == '__main__':
n = int(input())
integer_list = map(int, input().split())
input_list = [int(x) for x in integer_list]
t = tuple(input_list)``
print(hash(t))

VB.net read a text file and populate a combobox with specific extracted words

I have a problem which is giving me a headache. I really thought someone would have asked this already, but days of reading and testing has been fruitless.
I have a text file which starts:
"Determining profile based on KDBG search...
Suggested Profile(s) : WinXPSP2x86, WinXPSP3x86 (Instantiated with WinXPSP2x86)"
(The blank line between the two is not an error and neither are the spaces before 'Suggested')
I need to read the line starting 'Suggested...' only and extract every unique word starting 'Win' and populate a combobox with them. (i.e. 'WinXPSP2x86' and 'WinXPSP3x86')
I know i need to use the 'StreamReader' class and probably get a Regex going on, but, as a beginner, connecting it all together is beyond my knowledge at the moment.
Can anyone help? It would be much appreciated.
Imports System.IO
Public Class Form1
Private Sub Form1_Load( sender As Object, e As EventArgs) Handles MyBase.Load
' BASIC is case sensitive and e is parameter so we will start
' new variables with the letter f.
' Read all lines of file into string array F.
Dim F As String() = File.ReadAllLines("H:\Projects\35021241\Input.txt")
' F() is a 0 based array. Assign 3 line of file to G.
Dim G As String = F(2)
' On line 3 of file find starting position of the word 'win' and assign to H.
' TODO: If it is not found H will be -1 and we should quit.
Dim H As Integer = G.IndexOf("Win")
' Assign everything beginning at 'win' on line 3 to variable I.
Dim I As String = G.Substring(H)
' The value placed in delimiter will separate remaining values in I.
' Place C after ending quote to represent a single character as opposed to a string.
Dim Delimiter As Char = ","C
' J array will contain values left in line 3.
Dim J As String() = I.Split(Delimiter)
' Loop through J array removing anything in parenthesis.
For L = J.GetLowerBound(0) to J.GetUpperBound(0)
' Get location of open parenthesis.
Dim ParenBegin As Integer = J(L).IndexOf("(")
' If no open parenthesis found continue.
If ParenBegin <> -1 then
' Open parenthesis found. Find closing parenthesis location
' starting relative to first parenthesis.
Dim Temp As String = J(L).Substring(ParenBegin+1)
' Get location of ending parenthesis.
Dim ParenEnd As Integer = Temp.IndexOf(")")
' TODO: Likely an exception will be thrown if no ending parenthesis.
J(L) = J(L).Substring(0,ParenBegin) & J(L).Substring(ParenBegin + ParenEnd +2)
' Change to include text up to open parenthesis and after closing parenthesis.
End If
Next L
' UnwantedChars contains a list of characters that will be removed.
Dim UnwantedChars As String = ",()"""
' Check each value in J() for presence of each unwanted character.
For K As Integer = 0 to (UnwantedChars.Length-1)
For L = J.GetLowerBound(0) To J.GetUpperBound(0)
' Declare M here so scope will be valid at loop statement.
Dim M As Integer = 0
Do
' Assign M the location of the unwanted character or -1 if not found.
M= J(L).IndexOf(UnwantedChars.Substring(K,1))
' Was this unwanted character found in this value?
If M<>-1 Then
' Yes - where was it found in the value?
Select Case M
Case 0 ' Beginning of value
J(L) = J(L).Substring(1)
Case J(L).Length ' End of value.
J(L) = J(L).Substring(0,(M-1))
Case Else ' Somewhere in-between.
J(L) = J(L).Substring(0,M) & J(L).Substring(M+1)
End Select
Else
' No the unwanted character was not found in this value.
End If
Loop Until M=-1 ' Go see if there are more of this unwanted character in the value.
Next L ' Next value.
Next K ' Next unwanted character.
' Loop through all the values and trip spaces from beginning and end of each.
For L As Integer = J.GetLowerBound(0) To J.GetUpperBound(0)
J(L) = J(L).Trim
Next L
' Assign the J array to the combobox.
ComboBox1.DataSource = J
End Sub
End Class
As some have already suggested:
Use System.IO.File.ReadAllLines, if the file is not too big
Iterate through the array of lines
For each line, use the Split method to split on space
Check the first three characters of each word
This works but does of course need some error checking etc:
Dim lines() As String = System.IO.File.ReadAllLines("c:\temp\example.txt")
Dim lineWords() As String
For Each line As String In lines
lineWords = line.Split(New Char() {" "}, System.StringSplitOptions.RemoveEmptyEntries)
For Each word As String In lineWords
If word.Length > 3 Then
If word.Substring(0, 3).ToUpper = "WIN" Then
cmbWords.Items.Add(word)
End If
End If
Next
Next

how to skip multiple header lines using python

I am new to python. Trying to write a script that will use numeric colomns from a file whcih also contains a header. Here is an example of a file:
#File_Version: 4
PROJECTED_COORDINATE_SYSTEM
#File_Version____________-> 4
#Master_Project_______->
#Coordinate_type_________-> 1
#Horizon_name____________->
sb+
#Horizon_attribute_______-> STRUCTURE
474457.83994 6761013.11978
474482.83750 6761012.77069
474507.83506 6761012.42160
474532.83262 6761012.07251
474557.83018 6761011.72342
474582.82774 6761011.37433
474607.82530 6761011.02524
I'd like to skip the header. here is what i tried. It works of course if i know which characters will appear in the header like "#" and "#". But how can i skip all lines containing any letter character?
in_file1 = open(input_file1_short, 'r')
out_file1 = open(output_file1_short,"w")
lines = in_file1.readlines ()
x = []
y = []
for line in lines:
if "#" not in line and "#" not in line:
strip_line = line.strip()
replace_split = re.split(r'[ ,|;"\t]+', strip_line)
x = (replace_split[0])
y = (replace_split[1])
out_file1.write("%s\t%s\n" % (str(x),str(y)))
in_file1.close ()
Thank you very much!
I think you could use some built ins like this:
import string
for line in lines:
if any([letter in line for letter in string.ascii_letters]):
print "there is an ascii letter somewhere in this line"
This is only looking for ascii letters, however.
you could also:
import unicodedata
for line in lines:
if any([unicodedata.category(unicode(letter)).startswith('L') for letter in line]):
print "there is a unicode letter somewhere in this line"
but only if I understand my unicode categories correctly....
Even cleaner (using suggestions from other answers. This works for both unicode lines and strings):
for line in lines:
if any([letter.isalpha() for letter in line]):
print "there is a letter somewhere in this line"
But, interestingly, if you do:
In [57]: u'\u2161'.isdecimal()
Out[57]: False
In [58]: u'\u2161'.isdigit()
Out[58]: False
In [59]: u'\u2161'.isalpha()
Out[59]: False
The unicode for the roman numeral "Two" is none of those,
but unicodedata.category(u'\u2161') does return 'Nl' indicating a numeric (and u'\u2161'.isnumeric() is True).
This will check the first character in each line and skip all lines that doesn't start with a digit:
for line in lines:
if line[0].isdigit():
# we've got a line starting with a digit
Use a generator pipeline to filter your input stream.
This takes the lines from your original input lines, but stops to check that there are no letters in the entire line.
input_stream = (line in lines if
reduce((lambda x, y: (not y.isalpha()) and x), line, True))
for line in input_stream:
strip_line = ...

putting text,csv,excel file in pattern

I am beginner for real programming and have the ff problem
I want to read many instances stored in a file/csv/txt/excel
like the folloing
find<S>ing<G>s<p>
Then when I read this file it goes through each character and start from the six position and continue until the 11 position-the max size of a single row is 12
-,-,-,-,-,f,i,n,d,i,n,0
-,-,-,-,f,i,n,d,i,n,g,0
-,-,-,f,i,n,d,i,n,g,s,0
-,-,f,i,n,d,i,n,g,s,-,S//there is an S value next to the letter d
-,f,i,n,d,i,n,g,s,-,-,0
f,i,n,d,i,n,g,s,-,-,-,0
i,n,d,i,n,g,s,-,-,-,-,G // there is a G value here at th end of g
n,d,i,n,g,s,-,-,-,-,-,P */// there is a P value here at th end of s
Here is the code that I tried in python. but can be possible in c++, java, dotNet.
import sys
import os
f = open('/home/mm/exprimentdata/sample3.csv')// can be txt file
string = f.read()
a = []
b = []
i = 0
while (i < len(string)):
if (string[i] != '\n '):
n = string[i]
if (string[i] == ""):
print ' = '
if (string[i] = upper | numeric)
print rep(char).rjust(12),delimiter=','
a.append(n)
i = (i+1)
print (len(a))
print a
my question is how can I compare each string and assign a single char at the rightmost part (position 12 like above G,P,S)
how can I push one step back after aligning the first row?
how can i fix the length
please anyone see fragment and adjust to solve the above case
I don't understand your question.
But some advice:
Firstly, you should be closing the file after you open it.
f = open('/home/mm/exprimentdata/sample3.csv')// can be txt file
string = f.read()
**f.close()**
Secondly, your indentation is problematic. Whitespace matters in Python. (Maybe your real code is indented properly and it's just a StackOverflow thing.)
Thirdly, instead of using a while loop and incrementing, you should be writing:
for i range(len(string)):
# loop code
Fourthly, this line will never evaluate to True:
if (string[i] == ""):
string[i] will always be some character (or cause an out of bounds error).
I advise you read a Python tutorial before you try and write this program.