这段 Python 代码有什么作用?
我正在编写一个 python Hangman 程序,我希望能够从文件中随机生成一个单词,并且它可以工作。但我从网站上得到了一行代码,它可以帮助我做我需要做的事情,但我不知道如何。
谢谢
offset = random.randint(0, os.stat(filename)[6]) # ?????
fd = file(filename, 'rb')
fd.seek(offset)
fd.readline()
return fd.readline()
I am writing a python hangman program, and I wanted to be able to randomly generate a word from a file, and it works. But I got one line of this code off a website, and it helps me to do what I need to do, but I dont know how.
Thanks
offset = random.randint(0, os.stat(filename)[6]) # ?????
fd = file(filename, 'rb')
fd.seek(offset)
fd.readline()
return fd.readline()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
os.stat(filename)[6]
仅返回filename
命名的文件的大小(以字节为单位)。您可以阅读有关 os.stat() 的更多信息 文档。random.randint(...)
生成一个介于 0 和n
之间的随机整数,其中n
是通过获取的文件大小>os.stat()
。然后,代码会查找文件中的该(随机)位置。这个位置很可能位于一条线的中间。因此,代码读取部分行并将其丢弃。然后它读取下一行并返回它。
最后,代码有一个错误:如果随机位置落在文件的最后一行,则第二个
readline()
将没有任何内容可读取。编辑:此外,正如 @Russell Borogove 在评论中指出的,此方法不能确保以相同的概率选择行。
os.stat(filename)[6]
simply returns the size, in bytes, of the file named byfilename
. You can read more aboutos.stat()
in the documentation.random.randint(...)
generates a random integer between zero andn
, wheren
is the size of the file obtained viaos.stat()
.The code then seeks to that (random) position in the file. The chances are that this position is in the middle of a line. Therefore, the code reads the partial line and discards it. It then reads the next line and returns it.
Finally, the code has a bug: if the random position lands on the last line of the file, the second
readline()
will have nothing to read.edit: Also, as noted by @Russell Borogove in the comments, this method doesn't ensure that lines are chosen with equal probability.
为了扩展 aix 的答案,在文件“范围”内获得一个随机整数后,我们使用 fd.seek(offset) 转到该位置。我们使用 fd.readline() 删除当前所在的行,然后移至下一行。然后我们使用 fd.readline() 返回当前所在的整个行。
请注意,如果您最终到达文件的最后一行,您将返回一个空字符串。为了演示,请将偏移量设置为 os.stat(filename)[6] - 1 并使用 readline 两次。
To expand upon aix's answer, after we have a random integer within the "range" of the file, we go to that location with
fd.seek(offset)
. We usefd.readline()
to drop the line we are on, and move to the next one. Then we usefd.readline()
to return the entire current line we are on.Note that if you end up on the last line of the file, you will return an empty string. To demonstrate set your offset to
os.stat(filename)[6] - 1
and use readline twice.我尝试将其添加为注释,但无法包含代码示例。
这是您在修复的最后一行/第一行错误中包含的代码:
它没有解决 @russell-borogove 所描述的均匀性问题。
I tried to add this as a comment, but couldn't include a code example.
Here's the code you included with the last line/first line bug fixed:
It doesn't fix the uniformity problem as described by @russell-borogove.