用python连接从文件读取的字符串?

2024-10-02 12:26:48 发布

您现在位置:Python中文网/ 问答频道 /正文

Emacs的自动填充模式会分割行,使文档看起来更漂亮。我需要加入从文档中读取的字符串。

例如,(CR是回车,而不是真正的字符)

  - Blah, Blah, and (CR)
    Blah, Blah, Blah, (CR)
    Blah, Blah (CR)
  - A, B, C (CR) 
    Blah, Blah, Blah, (CR)
    Blah, Blah (CR)

用readlines()函数读入字符串缓冲区数组以生成

["Blah, Blah, and Blah, Blah, Blah, Blah, Blah", "A, B, C Blah, Blah, Blah, Blah, Blah"]

我曾想过让循环检查“-”以在它之前连接所有存储的字符串,但我希望Python有有效的方法来做到这一点。

添加:

基于kindall的代码,我可以得到我想要的如下。

lines = ["- We shift our gears toward nextGen effort"," contribute the work with nextGen."]
out = [(" " if line.startswith(" ") else "\n") + line.strip() for line in lines]
print out
res = ''.join(out).split('\n')[1:]
print res

结果如下。

['\n- We shift our gears toward nextGen effort', ' contribute the work with nextGen.']
['- We shift our gears toward nextGen effort contribute the work with nextGen.']

Tags: the字符串shiftwithouroutworkcr
3条回答

当我读到它时,您的问题是撤消硬包装并将每一组缩进行还原为一个软包装行。这是一种方法:

# hard-coded input, could also readlines() from a file
lines = ["- Blah, Blah, and", 
         "  Blah, Blah, Blah,",
         "  Blah, Blah",
         "- Blah, Blah, and",
         "  Blah, Blah, Blah,",
         "  Blah, Blah"]

out = [(" " if line.startswith(" ") else "\n") + line.strip() for line in lines]
out = ''.join(out)[1:].split('\n')

print out

我不确定你是否只想:

result = thefile.read()  

或者可能:

result = ''.join(line.strip() for line in thefile)  

或者别的什么。。。

使用file.readlines()。它返回一个字符串列表,每个字符串都是文件的一行:

readlines(...)
    readlines([size]) -> list of strings, each a line from the file.

    Call readline() repeatedly and return a list of the lines so read.
    The optional size argument, if given, is an approximate bound on the
    total number of bytes in the lines returned.

EDIT:readlines()不是最好的方法,正如评论中指出的那样。无视这个建议,用下面的建议代替

如果要使用emacs提供的输出作为python函数的输入,那么我将给出这个(如果emacs输出是一个长字符串):

[s.replace("\n", "") for s in emacsOutput.split('-')]

希望这有帮助

相关问题 更多 >

    热门问题