2014-02-24 24 views
-2

鑑於一首詩創建一個樂句怎麼會用下面我構建一個短語:Python的 - 從一首詩

這些數字是從哪裏樂句座標,行和列。 (1,1),(1,20),(3,60)

我的問題是沒有人有任何想法如何做到這一點?

+3

你能給我們提供更多信息嗎?這些座標是什麼?一個字?一句話?一封信?你會用座標給出的每個元素來構造你的短語嗎?如果是這樣,那麼座標是否引用了你的詩的字符串? – ZekeDroid

+0

您是否嘗試過一些代碼? – Totem

回答

2

好吧我要把你的問題射門被猜測:

讓你的詩是文本文件,使得其具有一堆話,並在末尾行字符的結尾(你寫通過只是進入)。該文件將是這個樣子:

This is a poem 
with many lines 
much much lines. 

現在您保存此文件,並在同一個文件夾中創建您的Python腳本,讓你可以輕鬆地打開它。

你的腳本現在將做兩件事:首先用你的詩打開文件,並將其存儲爲一個字符串列表。這意味着我們將把數組中的每個元素看作是你的詩中的一行(第一個座標點),並且每個元素都由單詞組成(第二個元素)。

所以在代碼的腳本是這樣的:

lines = [] 

with open('poem.txt', 'r') as poem: 
    for raw_line in poem: 
     line = raw_line.strip() 
     lines.append(line.split(" ")) 

如果我們打印我們的線陣列,我們得到:

[['This', 'is', 'a', 'poem'], ['wtih', 'many', 'lines'], ['much', 'much', 'lines.']] 

所以要完成,你的那句使得功能可以採取在數組座標,並將從線陣列中帶出字樣,如下所示:

def phrases(coords, poem): 
    '''Takes in an array of tuples with x and y coordinates where x is 
    the line number and y is the word on that line. Also takes in the 
    poem array''' 
    phrase = "" 
    for coordinate in coords: 
     line = coordinate[0] 
     word = coordinate[1] 
     phrase += poem[line][word] + ", " 

    # this is messy cause there's a lagging comma space at the end but 
    # figure that out later. 

    return phrase[:len(phrase)-2] 

如果我們給它我們的詩和三個座標是在範圍內將產生:

print phrases([(0,0), (1,2), (2,2)], poem) 

將產生一個短語:

This, lines, lines. 

總結:你的詩存儲爲行的列表,並且每個線由字。座標系是(行,字)。希望這是你的想法。

+0

謝謝,這看起來完全像我一直想要完成的一整天。那麼如果我不希望它在函數 – bisera

+0

中只是擺脫第一行並在它之前聲明座標數組。那部分應該很容易。 – ZekeDroid