bert-w/typomaniac

在文本中创建故意的拼写错误或打字错误。

v1.0.0 2020-05-16 19:49 UTC

This package is auto-updated.

Last update: 2024-09-17 05:27:30 UTC


README

Latest Stable Version Total Downloads License

一个为你创建故意的拼写错误/打字错误的库。

安装说明

composer require bert-w/typomaniac

快速开始

代码示例
$typomaniac = new \BertW\Typomaniac\Typomaniac([
    // Chance of an error (0 - 100), decided per character (default).
    'chance' => 2,
    // Usable mistakes (default).
    'mistakes' => [
        BertW\Typomaniac\Mistakes\CharacterAccents::class,
        BertW\Typomaniac\Mistakes\CharacterRepeat::class,
        BertW\Typomaniac\Mistakes\CharactersFlip::class,
        BertW\Typomaniac\Mistakes\CharacterSkip::class,
        BertW\Typomaniac\Mistakes\KeyboardTypo::class,
        BertW\Typomaniac\Mistakes\CharacterChangeCapitalization::class,
    ],
]);

$result = $typomaniac->typo('Please create random typo\'s in this text. The longer the text the more chance of an error!');

它有一个方便的 __toString() 方法来获取实际的字符串输出

echo $result;

// Result:
// 'Please create randoom typo's in tihs text. The longer the text the more chance of an  error!'

$result 还具有更多可能有用的属性

class Result {
    /** @var array List of used mistakes and their frequency. */
    public $usedMistakes = [];

    /** @var array List of available mistakes. */
    public $mistakes = [];

    /** @var int The chance of a mistake (0 - 100). */
    public $chance;
}

各种 错误 类型的说明

  • CharacterAccents: 对误输入的带音标字符进行错误处理。 ü => "u || u"
  • CharacterRepeat: 重复一个字符。 a => aa
  • CharactersFlip: 与前一个字符交换。 af => fa
  • CharacterSkip: 跳过一次按键(简单返回空字符串)。 a => (empty)
  • KeyboardTypo: 随机选择一个在QWERTY键盘上与另一个键物理上接近的键。 a => q
  • CharacterChangeCapitalization: 改变字符的大小写为小写或大写。 A => a

添加自己的错误类型

在尝试添加自己的错误类之前,请先阅读下面的 内部工作原理

要添加自己的拼写错误,只需创建一个类,并从 BertW\Typomaniac\Mistakes\Mistake 继承。请参阅源代码以获取示例。

// Add a mistake to the default mistake options (or assign it in the constructor).
$typomaniac->addMistake(\MyLibrary\FindSynonym::class);
$result = $typomaniac->typo(...);

内部工作原理

  • Typomaniac 逐字符循环输入字符串。
  • 对于每个字符,使用 $chance 属性来确定是否应发生错误。
  • 一旦发生这种情况,就会随机选择一个 Mistake 类作为当前活动的错误。
  • 只要 Mistake->end() 函数返回 false,它就会继续向错误 input 推送字符。这使得我们可以将任意长度的输入子串发送到错误类。例如,CharactersFlip 类期望2个字符,并返回翻转的2个字符。
  • 一旦 Mistake->end() 函数返回 true,错误类就会被要求对收到的输入进行错误处理。例如,对于给定的输入字符串 'fa'CharactersFlip 会返回 'af'
  • 循环继续,以便可以发生新的错误(或达到末尾,此时停止)。