如何调整间距以从chordpro 格式打印和弦以在歌词上方对齐?

问题描述 投票:0回答:1
const fs = require('fs');

const fileName = 'songs/Sister Golden Hair.txt';

fs.readFile(fileName, 'utf8', (err, data) => {
  if (err) {
    console.error(err);
    return;
  }

  // Split the file into lines
  const lines = data.split('\n');

  // Regular expression to match chords within square brackets
  const chordRegex = /\[([^\]]+)\]/g;

  // Iterate through each line and extract chords and lyrics
  for (let line of lines) {
    // Extract chords
    const chords = [];
    let chordMatch;
    let lastIndex = 0;

    while ((chordMatch = chordRegex.exec(line)) !== null) {
      const chord = chordMatch[1];
      const index = chordMatch.index;

      // Calculate spacing
      const spacing = ' '.repeat(index - lastIndex);
      chords.push(spacing + chord);

      lastIndex = index + chord.length;
    }

    // Remove chords from the line
    const lyrics = line.replace(chordRegex, '').trim();

    // Display chords above lyrics
    console.log(chords.join(' ') + '\n' + lyrics);
  }

  console.log("DONE");
});

Current output

Intended output

这是chordpro 文件。我认为问题在于代码没有补偿和弦的长度并增加了许多空格。

ChordPro example

谢谢!

javascript spacing chord
1个回答
0
投票

如果您可以使用几个 string.splits 而不是正则表达式,请看看。

编辑 - 添加代码以在和弦部分太大而无法容纳时向歌词添加空间。

let data = `Well I [E#min]tried to make it sunday but I [G#min]got so damned depressed
That I [A]set my sights on [E]monday and I [G#min]got myself undressed
I ain't ready for the alter, but I [C#min]do [G#min]agree
there's [A]times When a [F#min]woman sure can [A]be a friend of [E]mine [Esus2] [E]`;

// Split the file into lines
const lines = data.split('\n');
let result = [];

// Iterate through each line and extract chords and lyrics
for (let line of lines) {
  let lyricLine = "", chordLine = "";
  let parts = line.split("[");

  for (let part of parts) {
    let chord, lyric;
    if (part.indexOf("]") === -1) {
      chord = "";
      lyric = part;
    } else {
      [chord, lyric] = part.split("]");
    }

    let chordPart = chord + " ".repeat(Math.max(lyric.length - chord.length, 1));
    chordLine += chordPart;
    // add space to lyric if next chord would be pushed over
    lyricLine += lyric + " ".repeat(Math.max(0, chordPart.length - lyric.length))
  }
  result.push(chordLine);
  result.push(lyricLine);

}

document.querySelector("#output").innerText = result.join("\n");
<pre id="output"></pre>

© www.soinside.com 2019 - 2024. All rights reserved.