# 根据用户名和昵称预测性别

> 使用 V2 分析用户名和昵称：forceToGenderize、按条目设置的 AI、未知结果以及重复请求的费用。

Canonical HTML: https://www.genderapi.io/zh/blog/nicheng-he-yonghuming-de-xingbie-yuce

Last reviewed: 2026-09-29

## 发布信息

首次发布：2025-06-04T13:00:00.000Z

最后审核：2026-09-29T00:00:00.000Z

## 可以根据用户名判断性别吗？

在缺少真实名字时，GenderAPI 可以分析用户名、昵称或显示名称中的名字信号。请使用 API 的单条或批量请求，或使用 Excel/CSV 工作流，并把结果视为预测，而不是经过验证的身份。

## 昵称不是身份验证

@alice_smith 可能匹配到一个名字成分。对 prenses 使用 forceToGenderize 时，即使名字仍为 null，也可能返回预测结果。user47291 可能仍为未知结果。这些只是示例输入；我们不会预先为它们设定任何性别结果。

## 根据用户名预测性别是如何进行的？

系统会在用户名或显示名称中寻找可识别的名字成分和其他语言线索。标准 AI 回退会寻找可用的真实名字；使用 forceToGenderize 时，AI 可以在没有真实名字的情况下解读昵称。结果会连同上下文字段一起返回；对于随机或信息不足的输入，不应强行得出结果。

- 用户名：昵称或显示名称
- 信号分析：名字与上下文
- 预测：性别与置信度

## 选择适合您数据的方法

- [单条请求 通过 REST API 分析一个用户名。 查看 API 指南 →](https://www.genderapi.io/zh/docs/v2/gender-from-username)
- [批量请求 在一个结构化请求中发送多个条目。 查看批量指南 →](https://www.genderapi.io/zh/docs/v2/batch)
- [Excel/CSV 工作流 无需开发集成即可处理文件。 打开工具 →](https://app.genderapi.io/csv)

## 分四步分析 Excel 或 CSV 文件中的用户名

### 打开 Excel/CSV 工具

打开 GenderAPI 文件导入工具，并上传要处理的文件。

### 选择来源列

映射包含用户名、昵称或显示名称的列。

### 启用昵称解读

开启用于解读别名和社交媒体名称的选项。

### 先复核样本，再导出

先复核一批有代表性的记录样本，然后处理整个文件并下载补充后的数据。

新账户每天包含 200 个免费 API 积分，您可以先用样本测试工作流，再处理整个文件。

上传的 Excel 和 CSV 文件会在五天内从活跃系统中移除；导出结果后，您可以要求提前移除。访问受限的滚动备份可能额外保留最多 15 天。详情请参阅[隐私政策](https://www.genderapi.io/zh/privacy-policy)。

## 在缺少真实名字时作为辅助信号使用

当名字字段为空时，用户名分析可用于社交媒体、社区、游戏以及用户自建资料中的数据。如果您有更直接且经过授权的来源，例如真实名字或电子邮箱地址，请使用相应的端点。

- [从电子邮箱地址提取名字和性别信号](https://www.genderapi.io/zh/blog/extract-names-from-email-addresses)
- [批量处理 Excel 和 CSV 文件](https://www.genderapi.io/zh/blog/%E4%BD%BF%E7%94%A8-gender-api-%E7%A1%AE%E5%AE%9A-excel-csv-%E4%B8%AD%E5%A7%93%E5%90%8D%E7%9A%84%E6%80%A7%E5%88%AB)

## 不要把结果当作经过验证的身份

并非每个昵称都包含真实名字，文化联想各不相同，同一个表达在不同语言中也可能有不同含义。如果信号不足，请接受空结果，而不是把薄弱的数据变成确定的结论。

一起保存 V2 的置信度字段和来源字段，用您自己的数据衡量效果，不要依据这一信号对个人作出高影响的决定，例如涉及就业、信贷或医疗的决定。

## 分别保存来源数据与预测结果

请保留原始记录标识符。API 不会打开任何个人资料，不会验证账户持有人，也不会确认任何人的身份。只有在掌握可靠信息时才发送国家/地区上下文，不要根据域名或网站语言推断。

请以 type: username 发送用户名，不要发送个人资料的 URL。数据集查询会去除开头的 @，对文本进行规范化，并根据分隔符和数字生成候选项。标准请求可能从前缀和后缀中补充有限数量的匹配；forceToGenderize 不使用这些额外片段。如果有多行匹配，会选择记录出现次数最多的一行。电子邮箱地址请使用 type: email，真实姓名请使用 type: name。

| 示例输入 | 字段或选项 | 解读 |
| --- | --- | --- |
| @alice_smith | data.name / data.match | 保留原始用户名；不要把匹配到的片段当作经过验证的名字。 |
| prenses | forceToGenderize: true | 允许在没有真实名字的情况下解读昵称。可能返回性别而 data.name 为 null；不要为该用户编造名字。 |
| user47291 | data.result_status: unknown | 含义不明或信息不足的输入可能仍为未知结果。这并不是自动重新发送请求的理由。 |

### 选择处理模式与积分费用

单条请求默认使用 fallback；批量请求中的条目默认使用 off。forceToGenderize 对姓名、电子邮箱地址和用户名均为可选项；使用时请省略 ai_mode 或设置为 fallback，因为该选项不能与 off 或 always 组合。已完成的 unknown 结果同样计费。剩余余额为正数即可开始请求；操作完成后，余额可能变为负数。

| 选项 | 处理方式 | 每个完成条目的费用 |
| --- | --- | --- |
| options.ai_mode: off | 仅使用数据集 | 1 个积分 |
| options.ai_mode: fallback | 先查询数据集；无法确定性别时使用标准 AI 回退 | 包括 AI 在内共 1 个积分 |
| options.ai_mode: always | 直接使用 AI | 2 个积分 |
| forceToGenderize: true | 先查询数据集；之后解读昵称，不要求有真实名字 | 数据集足够时 1 个积分；使用 AI 时共 2 个积分 |

### 为批量请求中的每个条目设置选项

示例输入并不保证特定的预测结果。请在服务器环境中设置 GENDERAPI_API_KEY，不要把密钥放入公开的客户端代码。V1 和 V2 使用同一个账户 API 密钥和同一份余额。请通过 /api/v2/usage 检查密钥，并确认 meta.access.mode 的值为 api_key。

选择编程语言。[设置您的 API 密钥](https://www.genderapi.io/zh/docs/v2/authentication#environment-setup)，然后在您的服务器上运行示例。

每个预测请求（包括重试）都是一次新的计费操作。这些示例不会自动重试。发送下一个请求之前，请先检查计费状态。

### 运行之前：访问与错误处理

请在您的服务器上运行这些示例。在进程环境中将 GENDERAPI_API_KEY 设置为您现有的 API 密钥。请确认 meta.access.mode 为 api_key：无法识别的密钥可能会转为使用 IP 试用。

对于 HTTP 4xx 和 5xx JSON 响应，示例会保留错误响应体并以非零状态退出。重试前请检查 code、action 和 meta.usage.billing_status。对于 HTTP 200 的批量响应，还要检查每个条目的 data 或 error。

**cURL**

cURL 7.76+，在 POSIX shell 中运行。在终端中运行。[运行环境文档](https://curl.se/docs/manpage.html)

```bash
curl --silent --show-error --fail-with-body --max-time 30 \
  --request POST 'https://api.genderapi.io/api/v2/gender/batch' \
  --header "Authorization: Bearer ${GENDERAPI_API_KEY:?Set GENDERAPI_API_KEY}" \
  --header 'Content-Type: application/json' \
  --data '{
  "items": [
    {
      "id": "profile-001",
      "type": "username",
      "value": "@alice_smith",
      "options": {
        "ai_mode": "off"
      }
    },
    {
      "id": "profile-002",
      "type": "username",
      "value": "alexriver",
      "options": {
        "ai_mode": "fallback"
      }
    },
    {
      "id": "profile-003",
      "type": "username",
      "value": "prenses",
      "country": "TR",
      "forceToGenderize": true
    }
  ]
}'
```

**JavaScript / Node.js**

Node.js 22+；内置 fetch。保存为 example.mjs，然后运行 node example.mjs。[运行环境文档](https://nodejs.org/api/globals.html#fetch)

```javascript
// Server-side Node.js. Save as example.mjs.
const apiKey = process.env.GENDERAPI_API_KEY;
if (!apiKey) throw new Error("Set GENDERAPI_API_KEY");
const body = {
  "items": [
    {
      "id": "profile-001",
      "type": "username",
      "value": "@alice_smith",
      "options": {
        "ai_mode": "off"
      }
    },
    {
      "id": "profile-002",
      "type": "username",
      "value": "alexriver",
      "options": {
        "ai_mode": "fallback"
      }
    },
    {
      "id": "profile-003",
      "type": "username",
      "value": "prenses",
      "country": "TR",
      "forceToGenderize": true
    }
  ]
};

const response = await fetch("https://api.genderapi.io/api/v2/gender/batch", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${apiKey}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify(body),
  signal: AbortSignal.timeout(30_000),
  redirect: "error",
});
const raw = await response.text();
if (!(response.headers.get("content-type") ?? "").includes("json")) {
  throw new Error(`HTTP ${response.status}: expected JSON; request ID ${response.headers.get("x-request-id")}`);
}
const result = JSON.parse(raw); // Also accepts application/problem+json.
if (!response.ok) {
  console.error(`HTTP ${response.status}`, result);
  process.exitCode = 1; // A retry is a new operation; inspect billing first.
} else {
  console.log(JSON.stringify(result, null, 2));
  // For batches, inspect every item: HTTP 200 may contain item errors.
}
```

**Python**

Python 3.10+；标准库。保存为 example.py，然后运行 python3 example.py。[运行环境文档](https://docs.python.org/3/library/urllib.request.html)

```python
import json
import os
import sys
import urllib.error
import urllib.request

api_key = os.environ.get("GENDERAPI_API_KEY")
if not api_key:
    raise RuntimeError("Set GENDERAPI_API_KEY")
body = json.loads("{\"items\":[{\"id\":\"profile-001\",\"type\":\"username\",\"value\":\"@alice_smith\",\"options\":{\"ai_mode\":\"off\"}},{\"id\":\"profile-002\",\"type\":\"username\",\"value\":\"alexriver\",\"options\":{\"ai_mode\":\"fallback\"}},{\"id\":\"profile-003\",\"type\":\"username\",\"value\":\"prenses\",\"country\":\"TR\",\"forceToGenderize\":true}]}")

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

request = urllib.request.Request(
    "https://api.genderapi.io/api/v2/gender/batch",
    method="POST",
    data=json.dumps(body).encode("utf-8"),
    headers={
        "Authorization": "Bearer " + api_key,
        "Content-Type": "application/json",
    },
)
opener = urllib.request.build_opener(NoRedirect())
try:
    response = opener.open(request, timeout=30)
except urllib.error.HTTPError as error:
    response = error  # Keep the Problem Details body on non-2xx responses.
with response:
    status = response.status
    raw = response.read().decode("utf-8")
    if "json" not in response.headers.get("Content-Type", ""):
        raise RuntimeError(f"HTTP {status}: expected a JSON response")
    result = json.loads(raw)
print(json.dumps(result, indent=2), file=sys.stderr if status >= 300 else sys.stdout)
if not 200 <= status < 300:
    sys.exit(1)  # Inspect code, action and billing before retrying.
# For batches, inspect every item even when HTTP status is 200.
```

**PHP**

PHP 8+，需要 cURL 扩展。保存为 example.php，然后运行 php example.php。[运行环境文档](https://www.php.net/manual/en/book.curl.php)

```php
<?php
$apiKey = getenv('GENDERAPI_API_KEY');
if (!$apiKey) {
    throw new RuntimeException('Set GENDERAPI_API_KEY');
}
$body = json_decode('{"items":[{"id":"profile-001","type":"username","value":"@alice_smith","options":{"ai_mode":"off"}},{"id":"profile-002","type":"username","value":"alexriver","options":{"ai_mode":"fallback"}},{"id":"profile-003","type":"username","value":"prenses","country":"TR","forceToGenderize":true}]}', true, 512, JSON_THROW_ON_ERROR);

$ch = curl_init('https://api.genderapi.io/api/v2/gender/batch');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode($body, JSON_THROW_ON_ERROR),
]);
$raw = curl_exec($ch);
if ($raw === false) {
    throw new RuntimeException(curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE) ?: '';
curl_close($ch);
if (strpos($contentType, 'json') === false) {
    throw new RuntimeException("HTTP $status: expected a JSON response");
}
$result = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
$output = json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR) . PHP_EOL;
if ($status < 200 || $status >= 300) {
    fwrite(STDERR, $output); // Preserve the Problem Details body.
    exit(1);
}
echo $output;
// For batches, inspect every item; HTTP 200 can contain item errors.
```

**Java**

Java 17+；标准 HTTP 客户端。保存为 GenderApiExample.java，然后运行 java GenderApiExample.java。[运行环境文档](https://docs.oracle.com/en/java/javase/17/docs/api/java.net.http/java/net/http/HttpClient.html)

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

public class GenderApiExample {
    private static String requiredEnv(String name) {
        String value = System.getenv(name);
        if (value == null || value.isBlank()) throw new IllegalStateException("Set " + name);
        return value;
    }

    public static void main(String[] args) throws Exception {
        String apiKey = requiredEnv("GENDERAPI_API_KEY");
        String body = "{\"items\":[{\"id\":\"profile-001\",\"type\":\"username\",\"value\":\"@alice_smith\",\"options\":{\"ai_mode\":\"off\"}},{\"id\":\"profile-002\",\"type\":\"username\",\"value\":\"alexriver\",\"options\":{\"ai_mode\":\"fallback\"}},{\"id\":\"profile-003\",\"type\":\"username\",\"value\":\"prenses\",\"country\":\"TR\",\"forceToGenderize\":true}]}";
        HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .followRedirects(HttpClient.Redirect.NEVER)
            .build();
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.genderapi.io/api/v2/gender/batch"))
            .timeout(Duration.ofSeconds(30))
            .header("Authorization", "Bearer " + apiKey)
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8))
            .build();
        HttpResponse<String> response = client.send(request,
            HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
        if (!response.headers().firstValue("content-type").orElse("").contains("json")) {
            throw new IllegalStateException("HTTP " + response.statusCode() + ": expected JSON");
        }
        // JSON text; parse with your application's JSON library when integrating.
        if (response.statusCode() < 200 || response.statusCode() >= 300) {
            System.err.println(response.body()); // Includes Problem Details.
            System.exit(1);
        }
        System.out.println(response.body());
        // For batches, inspect each item's data or error, including on HTTP 200.
    }
}
```

**C# / .NET**

.NET 8+ 控制台应用。在控制台项目中作为 Program.cs 使用，然后运行 dotnet run。[运行环境文档](https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient)

```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

string RequiredEnv(string name) =>
    !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(name))
        ? Environment.GetEnvironmentVariable(name)!
        : throw new InvalidOperationException($"Set {name}");

var apiKey = RequiredEnv("GENDERAPI_API_KEY");
using var handler = new HttpClientHandler { AllowAutoRedirect = false };
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) };
using var request = new HttpRequestMessage(HttpMethod.Post, "https://api.genderapi.io/api/v2/gender/batch");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
request.Content = new StringContent("{\"items\":[{\"id\":\"profile-001\",\"type\":\"username\",\"value\":\"@alice_smith\",\"options\":{\"ai_mode\":\"off\"}},{\"id\":\"profile-002\",\"type\":\"username\",\"value\":\"alexriver\",\"options\":{\"ai_mode\":\"fallback\"}},{\"id\":\"profile-003\",\"type\":\"username\",\"value\":\"prenses\",\"country\":\"TR\",\"forceToGenderize\":true}]}", Encoding.UTF8, "application/json");

using var response = await client.SendAsync(request);
var raw = await response.Content.ReadAsStringAsync();
if (!(response.Content.Headers.ContentType?.MediaType?.Contains("json") ?? false))
    throw new InvalidOperationException($"HTTP {(int)response.StatusCode}: expected JSON");
using var result = JsonDocument.Parse(raw);
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine(result.RootElement); // Preserve Problem Details.
    Environment.ExitCode = 1;
}
else
{
    Console.WriteLine(result.RootElement);
    // For batches, inspect every item even on HTTP 200.
}
```

**Go**

Go 1.22+；标准库。保存为 main.go，然后运行 go run main.go。[运行环境文档](https://pkg.go.dev/net/http)

```go
package main

import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "strings"
    "time"
)

func requiredEnv(name string) string {
    value := os.Getenv(name)
    if value == "" { panic("Set " + name) }
    return value
}

func run() error {
    apiKey := requiredEnv("GENDERAPI_API_KEY")
    body := "{\"items\":[{\"id\":\"profile-001\",\"type\":\"username\",\"value\":\"@alice_smith\",\"options\":{\"ai_mode\":\"off\"}},{\"id\":\"profile-002\",\"type\":\"username\",\"value\":\"alexriver\",\"options\":{\"ai_mode\":\"fallback\"}},{\"id\":\"profile-003\",\"type\":\"username\",\"value\":\"prenses\",\"country\":\"TR\",\"forceToGenderize\":true}]}"
    request, err := http.NewRequest("POST", "https://api.genderapi.io/api/v2/gender/batch", strings.NewReader(body))
    if err != nil { return err }
    request.Header.Set("Authorization", "Bearer " + apiKey)
    request.Header.Set("Content-Type", "application/json")
    client := &http.Client{
        Timeout: 30 * time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    response, err := client.Do(request)
    if err != nil { return err }
    defer response.Body.Close()
    raw, err := io.ReadAll(response.Body)
    if err != nil { return err }
    if !strings.Contains(response.Header.Get("Content-Type"), "json") || !json.Valid(raw) {
        return fmt.Errorf("HTTP %d: expected a JSON response", response.StatusCode)
    }
    if response.StatusCode < 200 || response.StatusCode >= 300 {
        return fmt.Errorf("HTTP %d: %s", response.StatusCode, raw)
    }
    fmt.Println(string(raw))
    // For batches, inspect every item even on HTTP 200.
    return nil
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err) // Keep Problem Details for error handling.
        os.Exit(1)
    }
}
```

- [错误与重试指南 →](https://www.genderapi.io/zh/docs/v2/errors-and-retries)

### 处理列表结果与重复请求

POST /api/v2/gender/batch 使用 API 密钥时最多接受 50 个条目，使用 IP 试用时最多 10 个。请为每个条目分别提供 type、value 和 options。如需标准 AI 回退，请在每个条目中明确设置 fallback。id 在同一批次内必须唯一；index 在所提交的批次内从零开始。请单独保存您自己的任务标识符和来源行标识符。

HTTP 200 并不表示所有条目都已完成。请分别处理 identified、unknown 和 error 结果；meta.summary.succeeded 同时统计 identified 和 unknown。请综合评估 data.gender、source、confidence_kind、confidence、match 和 reason。不要把 AI 评分与数据集中的频率视为等同。

如果 meta.usage.billing_status 的值为 confirmed，只重试允许重新请求的操作错误。如果状态为 unconfirmed，或响应已丢失，请停止并检查计费情况。重新发送同一条目（包括已完成的 unknown 结果）会产生一次新的计费操作；切勿盲目重新发送整个列表。

[批量请求约定](https://www.genderapi.io/zh/docs/v2/batch) · [响应字段](https://www.genderapi.io/zh/docs/v2/responses) · [AI 选项](https://www.genderapi.io/zh/docs/v2/ai-options) · [准确性与置信度评估](https://www.genderapi.io/zh/accuracy-methodology) · [隐私政策](https://www.genderapi.io/zh/privacy-policy)

Excel 和 Google Sheets 插件以及其他现成集成可能使用各自的连接方式和结果格式。不要假定它们的输出遵循此 V2 JSON 结构；请查阅相应集成的当前指南。

## 根据用户名或昵称判断性别

### 可以根据用户名判断性别吗？

在 V2 中启用 forceToGenderize 后，系统会先查询数据集；如果无法确定性别，AI 可以在不要求真实名字的情况下解读昵称。结果仍可能为 unknown，也不是经过验证的身份。而标准 AI 回退则需要可用的真实名字。

### 哪些用户名能提供最有用的结果？

包含真实名字、可识别的昵称形式或清晰名字成分的值，可能提供更有用的信号。随机字符串和品牌名称并不总能得到结果。

### 可以通过 API 分析单个用户名吗？

可以。单条请求端点分析一个条目。多个条目可使用专门的批量请求端点。

### 可以导入 Excel 或 CSV 文件吗？

可以。在文件工具中，您可以选择用户名列或显示名称列，并启用昵称解读。

### 为什么应该一起保存 V2 的置信度字段和来源字段？

在 V2 中，data.confidence 的取值范围为 0 到 1。请结合 source 和 confidence_kind 评估该值，因为 AI 评分与数据集中的频率是不同的度量。请保留 unknown 结果和 reason 字段。

### 结果适合用于客户细分吗？

它可以作为聚合分析和数据补充中的辅助信号，但不应单独决定对个人有高影响的事项，也不应用来断定其身份。

### 可以免费试用吗？

GenderAPI 新账户每天包含 200 个免费 API 积分，您可以用它们通过 API 或文件测试有代表性的样本。
