首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在使用rPython包从R调用Python时转义引号

如何在使用rPython包从R调用Python时转义引号
EN

Stack Overflow用户
提问于 2016-05-13 03:04:12
回答 1查看 83关注 0票数 0

我试图使用rPython从R中执行以下命令,当适当定义变量时,各个行在Python中工作得很好。我已经意识到,逃避双引号可能是个问题,但我不清楚如何解决这个问题。

代码语言:javascript
复制
fname <- "some string"
rPython::python.assign("fstr", fname)
rPython::python.exec("print(fstr)")

这将在R控制台中正确地打印,因此让Python知道fstr的值并不是一个问题。

代码语言:javascript
复制
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))")

以下是错误:

代码语言:javascript
复制
File "<string>", line 2
    f.write('
            ^
SyntaxError: EOL while scanning string literal

我一直试图用不同的方式来逃避这句话,用“叶”来模仿我以前的问题,但没有取得什么成功。

我想我可以找到一种在R中做同样的操作的方法,但是我很好奇为什么这个方法不起作用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-13 03:21:35

有很多问题。问题不仅在于转义引号,还在于我未能逃脱换行符。要使用的正确代码是

代码语言:javascript
复制
rPython::python.exec("f.write(\'\\n\'.join(matched_lines))")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37200561

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档