【问题标题】:Creating more than one row in a CSV file/Chess database creation在 CSV 文件/国际象棋数据库创建中创建多于一行
【发布时间】:2022-01-26 01:14:30
【问题描述】:

我正在尝试创建一个数据库来训练基本的机器学习算法。但是,当我运行代码时,它只创建了两行,但我试图为游戏中的每个单独位置创建多行,并在最后对位置进行鱼分析。该代码似乎要进行三个动作,然后写入文件或为每个动作覆盖文件。我不能说它是哪一个。为了进一步说明,下面的示例是我编写的代码的输出,其中 number = 3:

但是,我正在寻找这样的东西:

0 1 2 3 4 5 6 7 8
P P p p
P P p p
P P p p

这是我的代码:

import chess
import chess.engine
import random
import numpy
import csv
from stockfish import Stockfish

header = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63]
data = []



def create_file(number):
  board = chess.Board()
  moves = 0
  turns = 0
  black_v = 0
  white_v = 0
  while moves < number:
    if chess.Board.is_game_over(board) == True:
      chess.Board.reset()
    if turns > 200:
      chess.Board.reset()
    for position in header:
      data.append(board.piece_at(position))

    with open('/content/Positions Data/position.csv', 'w', encoding='UTF8', newline='') as f:
        writer = csv.writer(f)
        header.append('sf')
        data.append((stockfish(board, 10))/100)
        writer.writerow(header)
        writer.writerow(data)
        data.clear()
        header.pop()
        turns = turns + 1
        moves = moves + 1
        random_move = random.choice(list(board.legal_moves))
        board.push(random_move)

【问题讨论】:

  • 您使用'w' 模式打开文件。这将覆盖所有先前写入的数据。因此,在您的 while 循环中,只有最后一次迭代将存储在文件中。

标签: python csv chess python-chess


【解决方案1】:

正如 Camaendir 在评论中指出的那样,您在每次移动迭代时都会打开输出文件。这将打开“用于创建”的文件,该文件会覆盖任何以前的数据。

此外,通过查看您的代码和您正在尝试做的事情,我发现有两种方法可以实现您想要的,并且您同时尝试这两种方法,这会产生其他问题。

打开 CSV 文件进行写入,并在使用 writer.writerow(stockfish(board, 10))/100) 处理棋盘/移动时循环遍历移动写入:

  1. 打开文件进行写入
  2. 从文件创建 csv.Writer
  3. 写你的标题
  4. 循环你的动作
    1. 处理移动/棋盘
    2. 写移动/棋盘
  5. 关闭文件

或者,处理所有附加到data的移动/棋盘,然后打开你的CSV文件并写入数据writer.writerows(data)

  1. 循环你的动作
    1. 处理移动/棋盘
    2. 将其附加到data
  2. 打开文件进行写入
  3. 从文件创建 csv.Writer
  4. 写你的标题
  5. data 写入所有行
  6. 关闭文件

【讨论】:

    猜你喜欢
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 2021-09-22
    • 1970-01-01
    相关资源
    最近更新 更多