Python lstrip Sometimes Removes Extra Character [duplicate] - python-2.7

This question already has answers here:
Python string.strip stripping too many characters [duplicate]
(3 answers)
Closed 7 years ago.
I have Python 2.7 code that operates on a list of files. In part of the code I strip away the directory information. Today I was surprised to find that code didn't work correctly, when the file names begin with "s". This sample code demonstrates the problem:
import os
TEST_RESULTS_DIR = ".." + os.sep + "Test Results"
filename = TEST_RESULTS_DIR + os.sep + "p_file.txt"
stripped_filename = filename.lstrip(TEST_RESULTS_DIR + os.sep)
print ("%s : %s") % (filename, stripped_filename)
filename = TEST_RESULTS_DIR + os.sep + "s_file.txt"
stripped_filename = filename.lstrip(TEST_RESULTS_DIR + os.sep)
print ("%s : %s") % (filename, stripped_filename)
When I run this code, I get this:
..\Test Results\p_file.txt : p_file.txt
..\Test Results\s_file.txt : _file.txt
Does anyone understand why?

Lstrip doesn't replace a string at the beginning of another string, it strips all characters that match the characters in the string argument from the string it is called on.
For example:
"aaabbbc".lstrip("ba") = "c"
Your directory has an s in it, so it get's striped, you would see the same result if the file started with a u or an e.

Related

system() cant run my program because space [duplicate]

This question already has answers here:
windows C system call with spaces in command
(1 answer)
C++ system() not working when there are spaces in two different parameters
(3 answers)
Closed 2 years ago.
i want run my program
so i do this program:
string zpath1, zpath2, zpath3, zpath3;
zpath1 = "C:\\Users\\";
zpath2 = zpath1 + getenv("USERNAME");
zpath3 = zpath2 + "\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\ConsoleApplication23.exe";
system(zpath3.c_str());
but i get a problem
'c:\User\adrian\AppData\Roaming\Microsoft\Windows\Start' is not knowing...
so i thing the problem is the space between "Start Menu"
how i can solve this problem ?
thank you
There are three possible solutions, one of two kinds of quotation marks or escape space character
zpath1 = "'C:\\Users\\";
// ^
zpath3 = zpath2 + "\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\ConsoleApplication23.exe'";
// ^
zpath1 = "\"C:\\Users\\";
// ^^
zpath3 = zpath2 + "\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\ConsoleApplication23.exe\"";
// ^^
zpath3 = zpath2 + "\\AppData\\Roaming\\Microsoft\\Windows\\Start^ Menu\\Programs\\Startup\\ConsoleApplication23.exe";
// ^
Thanks to #Eljay. Since the backlash \ is used in Windows as a path component separator, it can't be used as escape char, the carer symbol ^ is used as escape char in Windows command prompt.

Python - write filename / filepath into a textfile

I have some filenames defined in a Python script with tkinter who look like this:
def save_file(self):
self.filename = tkFileDialog.asksaveasfilename(title="Save...", filetypes=([("Excel Workbook","*.xlsx")]))
At the end the filename of these variables should be written out into a text file:
text_out = open('output.txt', 'w')
text_out.write("The first filename is " + self.filename + " + '\n')
text_out.write("The first pathname is " + self.filelocation + '\n')
text_out.close()
But it doesn't work. Has anyone any ideas? I have also tried it with:
text_out.write("The first filename is " + str(self.filename) + " + '\n')
but without the expedted result.
I tried it from the command line and got this error message:
SyntaxError: EOL while scanning string literal
This appears to mean that Python doesn't like having '\n' at the end of a bunch of strings stuck together with +. Try treating the items as a list and joining them, like this:
text_out = open('output.txt', 'w')
filewrite = ''.join([
'The first filename is ', self.filename, '\n',
'The first pathname is ', self.filelocation, '\n'])
text_out.write(filewrite)
text_out.close()
I got this idea from the Python Cookbook, and it works for me.

How do I dynamically search for text in a file and write to another file

I'll try to be as specific as I can. Keep in mind I just started learning this language last week so I'm not a professional. I'm trying to make a program that will read a vocabulary file that I created and write the definition for the word to another preexisting file with a different format.
Example of the two formats and what I'm trying to do here:
Word 1 - Definition
Word 1 (page 531) - Definition from other file
What I'm currently doing with it is I'm opening both files and searching a word based on user input, which isn't working. What I want to do is I want the program to go into the output file and find the word, then find the same word in the input file, get the definition only, and paste it into the output file. Then move to the next word and loop until it finds the end of file. I really don't know how to do that so I'm currently stuck. How would you python pros here on stackoverflow handle this?
Also for those who are suspicious of my reasons for this program, I'm not trying to cheat on an assignment, I'm trying to get some of my college work done ahead of time and I don't want to run into conflicts with my formatting being different from the teachers. This is just to save me time so I don't have to do the same assignment twice.
Edit 1
Here is the full code pasted from my program currently.
import os
print("Welcome to the Key Terms Finder Program. What class is this for?\n[A]ccess\n[V]isual Basic")
class_input = raw_input(">>")
if class_input == "A" or class_input == "a":
class_input = "Access"
chapter_num = 11
elif class_input == "V" or class_input == "v":
class_input = "Visual Basic"
chapter_num = 13
else:
print("Incorrect Input")
print("So the class is " + class_input)
i = 1
for i in range(1, chapter_num + 1):
try:
os.makedirs("../Key Terms/" + class_input + "/Chapter " + str(i) + "/")
except WindowsError:
pass
print("What Chapter is this for? Enter just the Chapter number. Ex: 5")
chapter_input = raw_input(">>")
ChapterFolder = "../Key Terms/" + class_input + "/Chapter " + str(chapter_input) + "/"
inputFile = open(ChapterFolder + "input.txt", "r")
outputFile = open(ChapterFolder + "output.txt", "w")
line = inputFile.readlines()
i = 0
print("Let's get down to business. Enter the word you are looking to add to the file.")
print("To stop entering words, enter QWERTY")
word_input = ""
while word_input != "QWERTY":
word_input = raw_input(">>")
outputArea = word_input
linelen = len(line)
while i < linelen:
if line[i] == word_input:
print("Word Found")
break
else:
i = i + 1
print(i)
i = 0
inputFile.close()
outputFile.close()
Not a python pro , however, I will try to answer your question.
output=[]
word=[]
definition=[]
with open('input.txt','r') as f:
for line in f:
new_line=re.sub('\n','',line)
new_line=re.sub('\s+','',line)
word.append(new_line.split("-")[0])
definition.append(new_line.split("-")[1])
with open('output.txt','r') as f:
for line in f:
new_line=re.sub('\n','',line)
new_line=re.sub('\s+','',line)
try:
index = word.index(new_line)
print index
meaning = definition[index]
print meaning
output.append(new_line+" - "+meaning)
except ValueError as e:
output.append(new_line+" - meaning not found")
print e
f=open("output.txt","w")
f.write("\n".join(output))
f.close()
Here, input.txt is the file where word and definition is present.
output.txt is the file which has only words ( it was unclear to me what output.txt contained I assumed only words ).
Above code is reading from output.txt , looking into input.txt and gets the definition if found else it skips.
Assumption is word and definition are separated by -
Does this helps?

C / C++ implement and pass code [duplicate]

This question already has answers here:
String literals C++?
(4 answers)
Closed 9 years ago.
I have interpreter from another language in C. I have to pass code (about 200 lines) from another language to this interpreter and here problem occur.
char* command_line[] = {
"",
"-e",
"print \"Hello from C!\\n\";"
};
This code is parse by:
(..)
parser(my_p, NULL, 3, command_line, (char **)NULL);
(...)
In code abobe I use array but even simple code have to be wrapped with \ before chars like " ; | \ etc.
How to avoid this problem and pass more then 200 multi row lines of code comfortable?
If you are using C++11, you can use raw string literals.
R"(print "Hello from C!\n";)"
Or you can simply put all the data into an external file and just read it on start. No need to escape any data there.
You could use the C preprocessor to do the stringification for you:
#define STRINGIFY(...) #__VA_ARGS__
#define STRINGIFY_NL(...) #__VA_ARGS__ "\n"
char* command_line[] = {
"",
"-e",
STRINGIFY(print "Hello from C!\n";), //< one element of the array
//< another element of the array
//< with embedded NL
STRINGIFY_NL(print "Hello from C!") //< no comma and the next line is glued
STRINGIFY ("for a second time";), //< end of other string
};
The only restrictions to observe would be that possible () have to balance inside the argument to STRINGIFY and that you'd have to place the macro on each line that you want to escape.
Unfortunately there is no support for literal strings or similar useful constructs in C, so if you want to write the interpreted code inside your C program you will have to be careful and escape quotes and slashes as you have stated.
The alternative is to write the code into a text file and treat it as an external resource file. You can read the resource file from inside your code into a string and then pass that to parser().
The ease of this depends on the platform you are using. Windows has good support for resource files and embedding them in to .exe files. I am sure it is possible with gcc too, but I haven't done it before. A bit vague I'm afraid, but I hope it helps.
You can use a script to take your text input, as a file, and stringify it (escaping double-quotes and newlines):
#!/usr/bin/env python
import sys
def main(argv = None):
if argv is None:
argv = sys.argv
if len(argv) < 2:
sys.stderr.write("Usage: stringify.py input.txt [... input.txt]\n")
sys.exit(1)
i = 1
while i < len(argv):
inname = argv[i]
firstline = True
try:
infile = open(inname, "r")
for line in infile:
line = line.replace('"', '\\"').replace('\n', '\\n')
sys.stdout.write('"{0}"\n'.format(line))
except IOError, msg:
sys.stderr.write("exception {0}\n".format(msg))
return 2
i = i + 1
return 0
if __name__ == "__main__":
sys.exit(main())

Increment Regex match using Regex.Replace

I'm creating a program in VB.NET to output multiple images. Some images will have the same file name. If there is multiple files with the same name I want to add "_1_" to the end of the file name. If the "_1_" file already exists I want to increment the 1 to be "_2_". If this file already exists I want to continue incrementing the number ultil it doesn't exist. So for example "filename", filename_1_", "filename_2_", etc. Here is the code that I have tried
Dim usedFiles As New List(Of String)
While usedFiles.Contains(returnValue)
If Regex.IsMatch(returnValue, "[_]([0-9]{1,})[_]$") Then
returnValue = Regex.Replace(returnValue, "[_]([0-9]{1,})[_]$", "_" + (CType("$1", Integer) + 1).ToString() + "_")
Else
returnValue += "_1_"
End If
End While
usedFiles.Add(returnValue)
The line that isn't working is:
returnValue = Regex.Replace(returnValue, "[_]([0-9]{1,})[_]$", "_" + (CType("$1", Integer) + 1).ToString() + "_")
which outputs "filename_2_" every time. I have also tried:
returnValue = Regex.Replace(returnValue, "[_]([0-9]{1,})[_]$", "_($1+1)_")
however this returns "filename_($1+1)_". I know I could just remove the "_" then add 1 to the number then put the "_" back on both sides, but I also know this can be done in other languages (like php) using the Regex.
Any ideas?
Thanks!
Ryan
I haven't taken the time to figure out what's wrong with your RegEx expression because it just seems silly to me. You're over thinking it. All you need to do is something simple like this:
Dim fileName As String = returnValue
Dim i As Integer = 0
While usedFiles.Contains(returnValue)
i = i + 1
returnValue = fileName + "_" + i.ToString() + "_"
End While