需要创建一个程序,打印出一个特定的字母开始的单词 [英] Need to create a program that prints out words starting with a particular letter

查看:159
本文介绍了需要创建一个程序,打印出一个特定的字母开始的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个程序,要求用户输入3个字母,然后询问用户一个字符串,然后打印出以三个字母开头的字符串中的所有单词...例如

 输入3个字母:AMD 
输入文字:Advanced Micro Devices是所有微软桌面的品牌
word:Advanced Micro Devices
word :所有微软桌面

非常简单。我是新来的,无法弄清楚...我的代码目前是什么...

  ipt1 = raw_input(Three字母:)##询问三个字母
ipt2 = raw_input(Text:)##询问文本
ipt1_split = ipt1.split()##将三个字母转换成列表
ipt2_split = ipt2.split()##将文本转换为列表

我不确定是否需要一个列表或不,任何人都知道如何解决这个问题?

解决方案

我会做这样的事情:



<$ p $ b $ = $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b words_lc = [x.lower()for x in word] #lowercase copy不区分大小写的检查

for x in range(len(words) - n + 1):
如果所有((words_lc [x + n] .startswith(letters [n])为范围(n)中的n)):
printmatch:,''.join(words [x:x + n ])

在这种情况下,字母的数量是动态的,如果你想把它固定为3 n 为三。如果要匹配字母大小写,请删除raw_input上的调用以及 all 中的比较。 / p>

I need a program that asks the user for 3 letters then asks the user for a string, then prints out all words in the string that start with the three letters...e.g

Enter 3 letters: AMD
Enter text: Advanced Micro Devices is a brand for all microsoft desktops
word: Advanced Micro Devices
word: all microsoft desktops

it's pretty simple. I'm new and having trouble figuring out how...my code is currently...

ipt1 = raw_input("Three letters: ") ## Asks for three letters
ipt2 = raw_input("Text: ") ## Asks for text
ipt1_split = ipt1.split() ## Converts three letters to list
ipt2_split = ipt2.split() ## Converts text to list

I'm not sure if you need a list or not, anyone know how to tackle this problem? Thanks!

解决方案

I'd do something like this:

letters = raw_input("letters: ").lower()
n = len(letters)
words = raw_input("text: ").split()
words_lc = [x.lower() for x in words] #lowercase copy for case-insensitive check

for x in range(len(words) - n + 1):
    if all((words_lc[x+n].startswith(letters[n]) for n in range(n))):
        print "match: ", ' '.join(words[x:x+n])

In this case the number of letters is dynamic, if you want it fixed to three just set n to three. If you want to match case of the letters, remove the lower calls on the raw_input and the comparison in all.

这篇关于需要创建一个程序,打印出一个特定的字母开始的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆