我试图使用rPython从R中执行以下命令,当适当定义变量时,各个行在Python中工作得很好。我已经意识到,逃避双引号可能是个问题,但我不清楚如何解决这个问题。
fname <- "some string"
rPython::python.assign("fstr", fname)
rPython::python.exec("print(fstr)")这将在R控制台中正确地打印,因此让Python知道fstr的值并不是一个问题。
rPython::python.exec("f = open(fstr+'_d.txt','r')")
# some lines in f contain the word "leaf" and also contain a character string in double quotes; if "leaf" is on a given line, I would like to extract that character string to a list
rPython::python.exec('matched_lines = [line.split("\"")[1] for line in f.readlines() if \"leaf\" in line]')
rPython::python.exec("f.close()")
rPython::python.exec("print(matched_lines)") # returns the expected output
# and then I'd like to write it to a file.
rPython::python.exec("f = open(fstr+'_d_char.txt','wb')")
rPython::python.exec("f.write('\n'.join(matched_lines))")以下是错误:
File "<string>", line 2
f.write('
^
SyntaxError: EOL while scanning string literal我一直试图用不同的方式来逃避这句话,用“叶”来模仿我以前的问题,但没有取得什么成功。
我想我可以找到一种在R中做同样的操作的方法,但是我很好奇为什么这个方法不起作用。
发布于 2016-05-13 03:21:35
有很多问题。问题不仅在于转义引号,还在于我未能逃脱换行符。要使用的正确代码是
rPython::python.exec("f.write(\'\\n\'.join(matched_lines))")https://stackoverflow.com/questions/37200561
复制相似问题