Python 3.3:如何从每行的第一个单词中提取第一个字母?

时间:2013-07-15 02:03:14

标签: python

我需要帮助解决这个问题。我正在尝试让我的程序从每一行的第一个Word中获取第一个字母,并将它们打印在一个字符串中。

例如,如果我在文本块中键入以下单词:

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)

3 个答案:

答案 0 :(得分:0)

您可以将输入存储为列表,然后从每个列表中获取第一个字符:

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



...


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

答案 1 :(得分: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]))

答案 2 :(得分:-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)

希望这有帮助