Python take the string of anything, ignoring all escape characters [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am trying to make a function that takes typically copy-pasted text that very often includes \n characters. An example of such is as follows:
func('''This
is
some
text
that I entered''')
The problem with this function is the text can sometimes be rather large, so taking it line by line to avoid ', " or ''' isn't plausible. A piece of text that can cause issues is as follows:
func('''This
is'''
some"
text'
that I entered''')
I wanted to know if there is any way I can take the text as seen in the second example and use it as a string regardless of what it is comprised of.
Thanks!

To my knowledge, you won't be able to paste the text directly into your file. However, you could paste it into a text file.
Use regex to find triple quotes ''' and other invalid characters.
Example python:
def read_paste(file):
import re
with open(file,'r') as f:
data = f.readlines()
for i,line in enumerate(data):
data[i] = re.sub('("|\')',r'\\\1',line)
output = str()
for line in data:
output += line
return output

Related

How to remove all characters in textfile after a specific character per line in python? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Suppose I have a textfile where each line is like this:
QWERTYUIOP",12345678901234567890
Some important text followed by the characters (",) then some other characters. How can I write a Python script to read each line of that textfile and remove all characters in each line that appear after (",)? I would also like to remove the ", characters themselves.
Then for each of the editted lines, I'd like to Base64 decode them and write them to a new textfile. I'm pretty sure I know how to do this part but I'm unsure about the editing part as described above.
Any assistance would be much appreciated!
file=open("file_name").readlines()
for i in file:
required_string = i.split('",')[0]
#your program to decode the required_string
I believe splitting lines by ", can help you overcome this problem. required_string is the string I believe you wanted. After this, you decode this string and save it in the text file as you wanted. Hope I solved the problematic part.

Identifying the correct line of a text file using re.compile [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I'm new to processing text files using Python and I got stuck on finding the correct line in a text file.
Looking at the image, I need to find a way that the block returns to me the line which contains the words:
'New packet was received' + something in between + the string stored in the variable stcrouter_line. (See picture).
Just with the variable, it returns 3 lines, which is correct in previously. Now, I just need to get the second line (with pattern above).
I believe I need the correct expression on the first line of the block:
line_regex = re.compile(stcrouter_line).
I'm not sure how to formulate this. Can anyone help me out, please?
Try to modify your code to:
line_regex = re.compile('New packet was received' + r'.*?' + stcrouter_line)
This is to match:
New packet was received match the text literally
r'.*? raw-string containing the regex .*? that will match any
texts in between the literal string above and your existing pattern.
With ? after * to make it the shortest match so that the match
will not overshoot to your existing pattern.
stcrouter_line your existing pattern

Reading a particular set from a file in python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I want read from file and store it as an array, for example :
test.txt :
1,2,7,2,3
5,8,1,6
7,4
7,4,4,4,4,4,4,4,4,0,5,4
Output:
{1,2,3,7}
{1,5,6,8}
{4,7}
{0,4,5,7}
How to fetch it as an array?
From what I understand, you want to parse your file in order to output the sets of numbers for each line, isn't it ?
If it is, a solution could be:
with open("test.txt") as f:
content = f.read()
l = [set(int(x) for x in l.split(','))
for l in content.splitlines()]
print (l)
This piece of code does not sort the set though, to do this, you will have to use frozenset as well as the sorted built-in function.
This should work.
Read from file
Split using newline character
Replace , in set
Like this
with open("test.txt",'r') as text_file: #reading in read mode
#to get the list of lines replacing new line
lines=text_file.read().split('\n')
#replace commas and make a set
set_of_lines = [ set(line.replace(",","")) for line in lines]
for line in set_of_lines:
print(line)

How do I read a text file into a string variable in Python starting at the second line? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I use the following code segment to read a file in python
file = open("test.txt", "rb")
data=file.readlines()[1:]
file.close
print data
However, I need to read the entire file (apart from the first line) as a string into the variable data.
As it is, when my files contents are test test test, my variable contains the list ['testtesttest'].
How do I read the file into a string?
I am using python 2.7 on Windows 7.
The solution is pretty simple. You just need to use a with ... as construct like this, read from lines 2 onward, and then join the returned list into a string. In this particular instance, I'm using "" as a join delimiter, but you can use whatever you like.
with open("/path/to/myfile.txt", "rb") as myfile:
data_to_read = "".join(myfile.readlines()[1:])
...
The advantage of using a with ... as construct is that the file is explicitly closed, and you don't need to call myfile.close().

I am trying to write a program to a file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Here's what I have.
"""
Author: Michael Wellman (wellmanm)
Title: pa10.py
Description: Deciphering a document using pennymath.
"""
def decode(inputfile,outputfile):
**inputfile = open("superDuperTopSecretStudyGuide.txt","rU").read()
outputfile = open("translatedguide.txt","w")**
count = 0
aList = []
for words in inputfile:
aList.append(words)
charCount = len(aList)
**outpufile.write(aList)**
while count<charCount:
print aList[count],
if (aList[count].isalpha()):
if (ord(aList[count])>90):
count = count + ord(aList[count])-95
else:
count = count + ord(aList[count])-63
else:
if (aList[count].isdigit()):
count = count + ord(aList[count])-46
else:
count = count + 6
**inputfile.close()
outputfile.close()**
The txt files are from my professor :P
The parts bolded are the most important, I believe.
Any thoughts?
Have you tried running the code?
I think if you would you'd get an error message about the line
outpufile.write(aList)
See, the doc string for file.write() method clearly states:
write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
You are supplying it a list instead of a str. Try changing it to
outpufile.write(''.join(aList))
or
outputfile.write(aList[-1])
or whatever fits your needs. Also, you never clear the list, so, as you iterate over inputfile, you'll write the first character, then the first and the second, then the first three, etc. Is that intended?
Lastly, you are trying to close inputfile which is actually a str, not a file, because file.read() method returns a str.
P.S. Please, never call your variable inputfile if it's a string and words if it's a single character. That will never help anyone.

Categories

Resources