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

2024-04-19 07:19: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.

我怎样才能把逗号后面的句子打印出来。这是逗号前的单词的定义。然后用随机函数随机打印出来。但只要打印一个定义。请帮忙。谢谢。你知道吗


Tags: orandthetexttxt定义withskill
1条回答
网友
1楼 · 发布于 2024-04-19 07:19:23

这样的怎么样?你知道吗

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]]

你的问题已经回答了一半。如何分割。 只需要两个基本要素。读入文本文件并分割一些字符串。你知道吗

相关问题 更多 >