【发布时间】: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