从大字符串读取行

时间:2012-07-05 15:41:22

标签: python python-2.7

我正在从文件中切出一大块文本。现在,块存储在变量中。像,

str="from child hood days i liked sweet and savoir. in the early days my mother cooked great deal of sweet meats in home and all my relatives had a nice taste for good sweets. even in remote assam town we thronged miles to procure good sweets. and my sweet eating habit was pretty known. in my childhood i could had as good as 30 to 40 rosgollas at one seating after a full course of lunch. though i was not among the best in my family."

但我现在想以与写作

相同的方式阅读每一行
for line in file:
     print line

我的问题是我们可以这样做,还是应该回写文件再进行操作?如果有人可以帮助你。

此致 Subhabrata Banerjee 古尔冈印度

3 个答案:

答案 0 :(得分:1)

将字符串转储到StringIO.StringIO,然后您可以对其使用文件操作。请注意,您的示例文本只有一行。

答案 1 :(得分:1)

for line in str.split('\n'):
    doit(line)

虽然这不是读取懒洋洋地解析。对于真的大块读取懒惰地解析:

for match in re.finditer(r'(.*)\n', str):
    print match.group(1)

答案 2 :(得分:0)

也许使用字符串标记生成器来处理“大字符串”,将其拆分为“较小的字符串”。这将使该过程更容易。顺便问一下,你在编码什么?