【问题标题】:Open a file, reformat, and write to a new file in Python 3在 Python 3 中打开文件、重新格式化并写入新文件
【发布时间】:2018-05-31 04:35:25
【问题描述】:

我对 Python 很陌生(几周)。我正在 Coursera 上为所有人开设 Python 课程,并决定将一些想法扩展为我想编写的应用程序。

我想取一个写引号的txt文件,去掉一些不必要的字符和换行符,然后将新格式化的字符串写入一个新文件。该文件将用于在终端中显示随机引号(此处不需要后者)。

txt 文件中的条目如下所示:

“The road to hell is paved with works-in-progress.”
—Philip Roth, WD some other stuff here
“Some other quote.”
—Another Author, Blah blah

我希望将以下内容写入新文件:

"The road to hell is paved with works-in-progress." —Phillip Roth
"Some other quote." —Another Author

我想删除引号和作者之间的换行符并替换为空格。我还想在作者之后从逗号中删除所有内容(所以它只是:引用[空格]作者)。该文件有 73 个,所以我想通过文件进行这些更改,然后用新格式化的引号写入一个新文件。最终输出将只是:“blah blah blah”-Author

我尝试了各种方法,目前正在 for 循环中遍历文件,将这两个段写入我正在考虑加入列表的列表中。但我被卡住了,也不确定这是否是矫枉过正。任何帮助将不胜感激。现在我有两个列表,我似乎无法加入它们,而且我不确定这样做是否正确。有什么想法吗?

到目前为止的代码:

fh = open('quotes_source.txt')


quote = list()
author = list()

for line in fh:

    # Find quote segment and assign to a string variable
    if line.startswith('“'):
        phrase_end = line.find('”')+1
        phrase_start = line.find('“')
        phrase = line[phrase_start:phrase_end]
        quote.append(phrase)

    # Find author segment and assign to a string variable
    if line.startswith('—'):
        name_end = line.find(',')
        name = line[:name_end]
        author.append(name)

print(quote)
print(author)

【问题讨论】:

  • 正则表达式的救援!
  • 内置 zip 可用于将两个列表连接在一起。
  • 还有,你确定phrase_end的计算是正确的吗?
  • ForceBru - 我担心 RegEx 会出现这种情况。我刚开始学习这些,还没有完全掌握它们的窍门。 quamrana:谢谢,我会查一下 zip。至于phrase_end,它之所以有效,是因为我需要最后一个引号。如果我删除 +1,它就会被删除。
  • 给出一个完整的例子?

标签: python string list file string-concatenation


【解决方案1】:

对于这样的简单任务,您不需要正则表达式,您实际上是在正确的轨道上,但是您在尝试解析所有内容而不是仅仅流式传输文件并决定剪切位置时陷入困境。

根据您的数据,您想在以(表示作者)开头的行进行剪切,并且您想从第一个逗号开始剪切该行。据推测,您也想删除空行。因此,一个简单的流修饰符看起来像:

# open quotes_source.txt for reading and quotes_processed.txt for writing
with open("quotes_source.txt", "r", encoding="utf-8") as f_in,\
        open("quotes_processed.txt", "w", encoding="utf-8") as f_out:
    for line in f_in:  # read the input file line by line
        line = line.strip()  # clear out all whitespace, including the new line
        if not line:  # ignore blank lines
            continue
        if line[0] == "—":  # we found the dash!
            # write space, everything up to the first comma and a new line in the end
            f_out.write(" " + line.split(",", 1)[0] + "\n")
        else:
            f_out.write(line)  # a quote line, write it immediately

仅此而已。只要数据中没有其他新行,它就会产生您想要的结果,即对于包含以下内容的 quotes_source.txt 文件:

“通往地狱的道路是由正在进行中的工程铺成的。”
—Philip Roth, WD 这里还有一些其他的东西

“邪恶胜利的唯一必要条件是好人什么都不做。”
——埃德蒙·伯克,不管有什么

“你对约翰·斯诺一无所知。”
——野人耶哥蕊特,《魔龙的狂舞》——乔治·R·R·马丁

它将生成一个quotes_processed.txt 文件,其中包含:

“通往地狱的道路是由正在进行中的工程铺成的。” ——菲利普·罗斯
“邪恶胜利的唯一必要条件是好人什么都不做。” ——埃德蒙·伯克
“你对约翰·斯诺一无所知。” ——野人耶哥蕊特

【讨论】:

  • 这很棒。完美运行,谢谢!我只需要弄清楚逻辑。新手有时很难概念化代码背后发生的事情。
【解决方案2】:
quote_line="“The road to hell is paved with works-in-progress.”\n—Philip Roth, WD some other stuff here\n"
quote_line=quote_line.replace("\n","")
quote_line=quote_line.split(",")

formatted_quote=""

如果您不确定该行中是否只有一个逗号。

  • “以牙还牙。”\n—某人罗斯,等等等等\n #只有一个逗号
  • “以牙还牙,以牙还牙”\n—某人罗斯,等等等等\n #不止一个逗号

    len_quote_list=len(quote_line)-1
    for part in range(0,len_quote_list):
        formatted_quote+=quote_line[part]
    formatted_quote+="\n"
    

formatted_quote=quote_line[0]+"\n"

【讨论】:

  • 感谢@imox 的建议,这不是我想要的。不过,我感谢你的努力。 :)
猜你喜欢
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
  • 2015-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多