以下是一个使用Python编写的程序示例,可以读取文本文件的内容并返回单词的索引和值:
def read_text_file(file_path):
word_index = 0
word_dict = {}
with open(file_path, 'r') as file:
for line in file:
words = line.strip().split() # 去除行首行尾空格并按空格分割单词
for word in words:
word_dict[word_index] = word
word_index += 1
return word_dict
# 示例用法
file_path = 'example.txt' # 替换为你的文件路径
result = read_text_file(file_path)
for index, word in result.items():
print(f"索引: {index}, 单词: {word}")
在这个示例中,read_text_file
函数接受一个文件路径作为参数,并打开文件进行读取操作。函数使用with open
语句打开文件,可以确保文件在读取完毕后被正确关闭。
然后,程序逐行读取文件内容,并使用strip
函数去除行首和行尾的空格。接着,使用split
函数按照空格分割每一行的单词,并使用循环遍历每个单词。每个单词都被添加到word_dict
字典中,使用word_index
作为键,word
作为值。word_index
递增以确保每个单词都有唯一的索引。
最后,函数返回word_dict
字典,其中包含每个单词的索引和值。
在示例的最后部分,我们使用read_text_file
函数读取文本文件,并将结果存储在result
变量中。然后,我们使用循环遍历result
字典中的每个键值对,并打印出索引和单词的值。