从文件中提取信息的最佳方法
例如我的文件是:
Game #51236595 Tourney #123698521 Hand #9865653215
player luisgustavo call
player otherplayer fold
player otherother check
我想以尽可能最好的方式获取信息。 请记住,所有文件都是这种格式。变化的是数字和球员
编辑:好的但这不是作业。 我已经这样做了几次,但我认为这不是最好的方法。
with open(".myfile", "r") as myfile:
for line in myfile:
if "Game" in line:
game_number = line[line.find('#')+1 : line.find("Tourney")-2]
tourney_number = line[line.find('Tourney #')+9 : line.find("Hand")-2]
hand_number = line[line.find('Hand #')+6 : ]
elif "player" in line:
player_name = line[line.find(' ')+1 : line.rfind(' ')]
player_action = line[line.rfind(' ')+1 : ]
该代码运行完美。但我不认为这是一个好的代码一定有更好的方法来做到这一点。
For example my file is:
Game #51236595 Tourney #123698521 Hand #9865653215
player luisgustavo call
player otherplayer fold
player otherother check
I want to get the information in best way possible.
Remember that all files are in this format. What changes are the numbers and players
EDIT: Ok but this is not a homework.
I've done this a few times but I do not think is the best way.
with open(".myfile", "r") as myfile:
for line in myfile:
if "Game" in line:
game_number = line[line.find('#')+1 : line.find("Tourney")-2]
tourney_number = line[line.find('Tourney #')+9 : line.find("Hand")-2]
hand_number = line[line.find('Hand #')+6 : ]
elif "player" in line:
player_name = line[line.find(' ')+1 : line.rfind(' ')]
player_action = line[line.rfind(' ')+1 : ]
The code works perfectly. But I do not think it's a good code must have a better way to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试类似的方法
This using
split()
[ docs] 并且更加Pythonic。Try something like
This uses
split()
[docs] and is much more pythonic.您可以将
csv.reader
与自定义方言结合使用,以获得已排序大量详细信息的通用解决方案。You can use
csv.reader
with a custom dialect for a general solution with a lot of the details already sorted.基于上面 @brc 给出的答案:
这清楚地以最小的开销提取了您需要的部分。当然,您还需要对这些值进行实际操作。另外,我假设一个文件中可以有多个“游戏”行。如果这不是真的,你可以在第一行检查它。
Building on the answer given by @brc above:
This clearly extracts the pieces you need with a minimum of overhead. Of course, you'll also need to actually do something with the values. Also, I'm assuming there can be multiple "game" lines in a file. If that's not true, you can just check for it in the first line.