我已將一篇小說粘貼到文本文件中。 我想爲他們保留在每個頁面的頂部出現的(僅僅取消其在這些線路出現也將這樣做)刪除包含下列句子的所有行:Python從長長的字符串中刪除單詞的完整句子
"Thermal Molecular Movement in , Order and Probability"
"Molecular and Ionic Interactions as the Basis for the Formation"
"Interfacial Phenomena and Membranes"
我第一次嘗試是如下:
mystring = file.read()
mystring=mystring.strip("Molecular Structure of Biological Systems")
mystring=mystring.strip("Thermal Molecular Movement in , Order and Probability")
mystring=mystring.strip("Molecular and Ionic Interactions as the Basis for the Formation")
mystring=mystring.strip("Interfacial Phenomena and Membranes")
new_file=open("no_refs.txt", "w")
new_file.write(mystring)
file.close()
但是這對輸出文本文件沒有影響......內容是完全沒有改變......我覺得這很奇怪,因爲下面的例子玩具正常工作:
>>> "Hello this is a sentence. Please read it".strip("Please read it")
'Hello this is a sentence.'
正如上面沒有工作,我嘗試以下代替:
file=open("novel.txt", "r")
mystring = file.readlines()
for lines in mystring:
if "Thermal Molecular Movement in , Order and Probability" in lines:
mystring.replace(lines, "")
elif "Molecular and Ionic Interactions as the Basis for the Formation" in lines:
mystring.replace(lines, "")
elif "Interfacial Phenomena and Membranes" in lines:
mystring.replace(lines, "")
else:
continue
new_file=open("no_refs.txt", "w")
new_file.write(mystring)
new_file.close()
file.close()
但這種嘗試我得到這個錯誤:
類型錯誤:預期字符串或其他字符緩衝區對象
這是非常感謝:你知道我會如何刪除整條線,而不僅僅是模式,例如「第3.1節」生物系統的能量和動力學「,第337頁」 - 刪除整條線...我試過「mystring.pop(i)」,但它給出:AttributeError:'str'對象沒有屬性'pop' –