2016-01-23 77 views
-1
f = open("Trades.txt","r") 
writer = open("trading.txt","w") 
options = input("A:Check trades for 1 or more players/B:Check trades between 2 players: ").lower() 

if options == 'b': 
    player1 = input("Enter the name of player 1: ") 
    player2 = input("Enter the name of player 2: ") 
    for lines in f: 
     if player1 and player2 in lines: 
      writer.write(lines) 

文本文件看起來是這樣的:寫從文件中的所有行到一個文件中,直到達到一個特定的字符串

======================= 
[time] player trading with playerx 
(To: player, From: playerx) 
item 
======================= 
[Jan 13, 2016 11:53:49 PM Central European Time] y trading with x 
(To: x, From: y) 
item 
======================= 

用戶將被要求輸入2名在文本文件中找到。

這兩個名字必須在我已經完成的文本中找到。

然後,具有名稱的行後面的行將不得不寫入文件,直到達到「=======================」。

因此,寫入的數據會看起來像:

[time] player trading with playerx 
(To: player, From: playerx) 
item 

在此先感謝

PS名稱後的行數會不同,所以不能像寫後線的一組量匹配

+0

Stack Overflow是不是免費的代碼編寫的服務。請向我們展示您解決此問題的嘗試,並精確詢問您遇到的問題。 –

+0

我有嗎?看看第一位 – I3uzzzzzz

+0

可能重複[如何測試一個變量對多個值?](http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-多值) – MattDMo

回答

0

兩件事情來解決

第一

if player1 and player2 in lines: 

是錯誤的,也許這是更好的

if player1 in lines and player2 in lines: 

停車時=======================中被發現環像

lines = lines.strip() 
if lines == '=======================': 
    break 

的「帶()」函數從輸入文件中的新行左右就行了精確匹配工作正常

只是要清楚代碼

for lines in f: 
    if player1 and player2 in lines: 
     writer.write(lines) 

被替換

for lines in f: 
    if player1 in lines and player2 in lines: 
    lines = lines.strip() 
    if lines == '=======================': 
     break 
    writer.write(lines) 
+0

對不起,但我在哪裏添加額外的代碼給你? – I3uzzzzzz

+0

我已經添加了更多關於添加更改的詳細信息 – Vorsprung

0

由於源文件的對象是一個迭代器,你可以在任何地方使用它,不僅在for line in f聲明。

要消耗迭代,直到出現條件,可以使用​​函數。

只要謂詞爲真,就創建一個從迭代器返回元素的迭代器。

takewhile將創造新的迭代器,但它的副作用源迭代會被消耗掉。在文件對象情況下 - 它會讀取行並移動內部文件指針。在耗盡takewhile迭代器之後,內部文件指針會指向===之後的第一行。

代碼將類似這樣的:

import itertools 

player1 = "x" 
player2 = "y" 
with open("Trades.txt") as src, open("trading.txt", "w") as dst: 
    for src_line in src: 
     if player1 in src_line and player2 in src_line: 
      dst.write(src_line) 
      for line in itertools.takewhile(lambda s: not s.startswith("======================="), src): 
       dst.write(line) 
相關問題