2013-07-15 135 views
0

我需要此問題的幫助。我試圖讓我的程序抓住每一行上第一個字的第一個字母,並將它們打印在單個字符串中。Python 3.3:如何從每行的第一個字提取第一個字母?

例如,如果我在文本塊中鍵入下面的話:

People like to eat pie for three reasons, it tastes delicious. The taste is unbelievable, next pie makes a 
great dessert after dinner, finally pie is disgusting. 

結果應該是「PG」這是一個小的例子,但你的想法。

我開始使用代碼,但我無法確定要去哪裏。

#Prompt the user to enter a block of text. 
done = False 
print("Enter as much text as you like. Type EOF on a separate line to finish.") 
textInput = "" 
while(done == False): 
    nextInput= input() 
    if nextInput== "EOF": 
     break 
    else: 
     textInput += nextInput 

#Prompt the user to select an option from the Text Analyzer Menu. 
print("Welcome to the Text Analyzer Menu! Select an option by typing a number" 
    "\n1. shortest word" 
    "\n2. longest word" 
    "\n3. most common word" 
    "\n4. left-column secret message!" 
    "\n5. fifth-words secret message!" 
    "\n6. word count" 
    "\n7. quit") 

#Set option to 0. 
option = 0 

#Use the 'while' to keep looping until the user types in Option 7. 
while option !=7: 
    option = int(input()) 

#I have trouble here on this section of the code. 
#If the user selects Option 4, extract the first letter of the first word 
    #on each line and merge into s single string. 
    elif option == 4: 
     firstLetter = {} 
     for i in textInput.split(): 
      if i < 1: 
       print(firstLetter) 
+0

如何從您發佈的示例中獲得''Pg''?我認爲你需要更好地設置樣本文本的格式來顯示你的意思。我建議使用與用於顯示代碼 – inspectorG4dget

+0

@ inspectorG4dget相同的格式:現在,請看一看。我已經重新格式化它以匹配問題測試的描述。希望我對我的假設是正確的。 – Tadeck

回答

0

您可以輸入存儲爲一個列表,然後從每個列表中得到第一個字符:

textInput = [] 
while(done == False): 
    nextInput= input() 
    if nextInput== "EOF": 
     break 
    else: 
     textInput.append(nextInput) 



... 


print ''.join(l[0] for l in textInput) 
+0

使用'textInput.append(nextInput)'而不是'textInput + = [nextInput]'。實際上不需要創建一個新列表來將一個項目追加到現有列表中。 – Blender

+0

好點。謝謝! – jh314

+0

@Blender:我認爲'__iadd__'是一個就地擴展的列表。我找不到鏈接。你能否詳細說明一下? – inspectorG4dget

0

我會通過使線而不是一個字符串列表開始:

print("Enter as much text as you like. Type EOF on a separate line to finish.") 

lines = [] 

while True: 
    line = input() 

    if line == "EOF": 
     break 
    else: 
     lines.append(line) 

然後,你可以得到的第一個字母一個循環:

letters = [] 

for line in lines: 
    first_letter = line[0] 
    letters.append(first_letter) 

print(''.join(letters)) 

或者更簡潔:

print(''.join([line[0] for line in lines])) 
+0

有沒有辦法讓程序在單個字符串上工作? – user2581724

+0

@ user2581724:爲什麼?你可以,但不能以某種方式使各條線路可用。 – Blender

-1

這是非常簡單的:

with open('path/to/file') as infile: 
    firsts = [] 
    for line in infile: 
     firsts.append(line.lstrip()[0]) 
print ''.join(firsts) 

當然,你可以做同樣的事情有以下兩班輪:

with open('path/to/file') as infile: 
    print ''.join(line.lstrip()[0] for line in infile) 

希望這幫助

相關問題