簡體   English   中英

python腳本,用於在另一個文件中打印兩個連續的單詞和文本

[英]python script for printing two consecutive word with the text in another file

我是 python 新手,我需要創建一個腳本,其中有兩個文件:第一個文件僅包含以下格式的位置:

1 London
2 United Kingdom
3 Rome
4 USA
5 Italy
6 Texas

在第二個文件中,我有下面給出的文本:

MATCH p=AllShortestPaths((c:City {name:"%a"})-[*]->(c:City {name:"%b"}))  
return p;

所以目前,我想創建一個輸出文件,它應該從第二個文件復制文本並替換第一個文件中的第一個位置和第二個位置,而不是文本中的 $a 和 %b 。

並且它應該繼續做這件事,就像第一個循環應該檢索location 1location 2然后是下一個location 1location 3依此類推。 列表完成后,從location 2location 3開始,然后是location 2location 4 ,依此類推,直到檢索到所有單詞。

你的問題很復雜,但我認為這兩件事應該對你有幫助:

組合可迭代

使用 itertools.combinations 獲取所有對的可迭代性:

代碼:

from itertools import combinations
list(combinations([1,2,3],2))

輸出:

[(1, 2), (1, 3), (2, 3)]

代替

代碼:

"spam Spanish cheese Spanish".replace("Spanish","inquisition")

輸出:

"spam inquisition cheese inquisition"

所以建議的代碼如下所示:

from itertools import combinations

with open("first_file") as f:
    cities = (city.strip() for city in f.readlines())

with open("second_file") as f:
    cypher_query = f.readlines()

with open("third_file","w") as f:
    for city1,city2 in combinations(cities,2):
        f.writelines(line.replace("%a",city1).replace("%b",city2) for line in cypher_query)
        f.write("\n")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM