2013-07-15 152 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) 

希望这帮助

相关问题