如何拆分文本文件和随机打印内容[Python]

时间:2015-01-20 11:09:23

标签: python

我有一个包含以下内容的文本文件:

text.txt

achievement , a thing done successfully with effort, skill, or courage.
skill , the ability to do something well; expertise
jump , push oneself off a surface and into the air by using the muscles in one's legs and feet.

如何在逗号后打印句子。这是逗号之前的单词的定义。然后用随机函数随机打印它们。但只需打印一个定义。请帮忙。感谢。

1 个答案:

答案 0 :(得分:1)

这样的事情怎么样?

from random import randint

infilename = "test.txt"
allLinesList = []
with open(infilename, "r") as infile:
    allLinesList = infile.readlines()

allWords = []
definitionDic = {}

for line in allLinesList:
    splitted = line.split(",", 1)
    allWords.append(splitted[0].strip())
    definitionDic[splitted[0].strip()] = splitted[1].strip()

print "A random definition is printed:"
index = randint(0, len(allWords)-1)
print "Word: " + allWords[index] + " / Definition: " + definitionDic[allWords[index]]

在你的问题中,你已经回答了一半的问题。怎么分裂。 只需2个基础知识。读入文本文件并拆分一些字符串。