我想找到一个以字母开头的文字。例如'B',在找到它们之后,我想按字母顺序排序。用python
答案 0 :(得分:1)
def get_words(filename, char)
f = open(filename)
all_words = []
word_sep = ' ' # assuming words are separated by space in your file
for line in f:
line_words = [word for word in line.rstrip().split(word_sep) if word.startswith(char)]
all_words.extend(line_words)
f.close()
return sorted(all_words)
get_words('words.txt', 'B')
答案 1 :(得分:-1)
lst = []
filename = raw_input('Enter filename')
f = open(filename)
for line in f:
line = line.rstrip()
line = line.split()
for word in line:
if "B" in word:
lst.append(word)
lst.sort()
print lst
从文件中提取每一行。将该行拆分为一个列表,在列表中运行一个循环并检查列表中的单词是否包含字母B.如果是,则将该单词附加到空列表中。对附加列表进行排序并打印出来。