我试图写一个一致性程序,我试图让shell打开一个文件,阅读它,并解释内容是什么。然后我希望它按字母顺序打印出单词,以及单词相对于文本的位置。到目前为止我有这个:
1
到目前为止,代码按字母顺序正确地给出了单词;但是,它并没有给我正确的位置。我对python有些新意,所以如果你能尝试保持它有点基础,那将是值得赞赏的。我还想保持标点符号,使其更加独特。"
答案 0 :(得分:0)
据我所知,您关注文件中存在的单词的实际位置,同时您希望按字母顺序打印单词。您可以使用以下代码:
请注意,我们总是会对每个单词进行计数,这是存储该单词位置的列表的长度。
# allwords is a dictionary which uses word as the key and the list of position of the word in the file as the value.
# The position will be recored as (line_number, word_number) tuple where word_number is position of the word in that particular line.
allwords = {}
# Get the index of the line as well.
for lineno,line in enumerate(handle.readlines()):
words = line.split()
# Get the word index as well.
for wordno,w in enumerate(words):
w = w.lower()
# Make the position tuple and append in the list of appearances for that particular word.
position = (lineno+1, wordno+1)
if w not in allwords.keys():
allwords[w] = []
allwords[w].append(position)
for key in sorted(allwords.keys()):
print(key + " appeared " + str(len(allwords[key])) + " number of times and positions are:")
for tup in allwords[key]:
print(tup)