跳到正文
cccskills
免费在 GitHub 公开

python-scala-libraries

Map common Python modules and idioms to Scala libraries and approaches. Use examples to translate JSON, dates, files, regular expressions, HTTP requests, logging, tests, configuration, command-line arguments, and asynchronous work.

中文简介正在准备中。当前显示英语简介。

原文查看原文说明

Guide for mapping common Python libraries and idioms to Scala equivalents. Use when converting Python code that uses standard library modules (json, datetime, os, re, logging) or needs equivalent Scala libraries for HTTP, testing, or async operations.

benchflow-ai/skillsbench星标 1,872(GitHub 1,872 + cccskills 0)

实测评分 未实测

查看安装方法

适用场景

  • Translating Python JSON and date handling to Scala
  • Finding Scala equivalents for file and regex operations
  • Porting HTTP requests and logging code
  • Mapping pytest examples to ScalaTest or munit
  • Converting Python async workflows to Scala

包含的文件(1)

  • SKILL.md8.7 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

Python to Scala Library Mappings

JSON Handling

# Python
import json

data = {"name": "Alice", "age": 30}
json_str = json.dumps(data)
parsed = json.loads(json_str)

# With dataclass
from dataclasses import dataclass, asdict

@dataclass
class Person:
    name: str
    age: int

person = Person("Alice", 30)
json.dumps(asdict(person))
// Scala - circe (most popular)
import io.circe._
import io.circe.generic.auto._
import io.circe.syntax._
import io.circe.parser._

case class Person(name: String, age: Int)

val person = Person("Alice", 30)
val jsonStr: String = person.asJson.noSpaces
val parsed: Either[Error, Person] = decode[Person](jsonStr)

// Scala - play-json
import play.api.libs.json._

case class Person(name: String, age: Int)
implicit val personFormat: Format[Person] = Json.format[Person]

val json = Json.toJson(person)
val parsed = json.as[Person]

Date and Time

# Python
from datetime import datetime, date, timedelta
import pytz

now = datetime.now()
today = date.today()
specific = datetime(2024, 1, 15, 10, 30)
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
parsed = datetime.strptime("2024-01-15", "%Y-%m-%d")
tomorrow = now + timedelta(days=1)

# Timezone
utc_now = datetime.now(pytz.UTC)
// Scala - java.time (recommended)
import java.time._
import java.time.format.DateTimeFormatter

val now = LocalDateTime.now()
val today = LocalDate.now()
val specific = LocalDateTime.of(2024, 1, 15, 10, 30)
val formatted = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
val parsed = LocalDate.parse("2024-01-15")
val tomorrow = now.plusDays(1)

// Timezone
val utcNow = ZonedDateTime.now(ZoneOffset.UTC)
val instant = Instant.now()

File Operations

# Python
from pathlib import Path
import os

# Reading
with open("file.txt", "r") as f:
    content = f.read()
    lines = f.readlines()

# Writing
with open("file.txt", "w") as f:
    f.write("Hello")

# Path operations
path = Path("dir/file.txt")
path.exists()
path.parent
path.name
path.suffix
list(Path(".").glob("*.txt"))
os.makedirs("new/dir", exist_ok=True)
// Scala - java.nio.file (standard) + scala.io
import java.nio.file.{Files, Path, Paths}
import scala.io.Source
import scala.util.Using

// Reading
val content = Source.fromFile("file.txt").mkString
Using(Source.fromFile("file.txt")) { source =>
  source.getLines().toList
}

// Writing
Files.writeString(Paths.get("file.txt"), "Hello")

// Path operations
val path = Paths.get("dir/file.txt")
Files.exists(path)
path.getParent
path.getFileName
// Extension: path.toString.split('.').lastOption
Files.createDirectories(Paths.get("new/dir"))

// os-lib (better alternative)
// import os._
// os.read(os.pwd / "file.txt")
// os.write(os.pwd / "file.txt", "Hello")

Regular Expressions

# Python
import re

pattern = r"\d+"
text = "abc123def456"

# Search
match = re.search(pattern, text)
if match:
    print(match.group())

# Find all
matches = re.findall(pattern, text)

# Replace
result = re.sub(pattern, "X", text)

# Split
parts = re.split(r"\s+", "a b  c")
// Scala
val pattern = """\d+""".r
val text = "abc123def456"

// Search
pattern.findFirstIn(text) match {
  case Some(m) => println(m)
  case None => ()
}

// Find all
val matches = pattern.findAllIn(text).toList

// Replace
val result = pattern.replaceAllIn(text, "X")

// Split
val parts = """\s+""".r.split("a b  c").toList

// Pattern matching with regex
val datePattern = """(\d{4})-(\d{2})-(\d{2})""".r
"2024-01-15" match {
  case datePattern(year, month, day) => s"$year/$month/$day"
  case _ => "no match"
}

HTTP Requests

# Python
import requests

response = requests.get("https://api.example.com/data")
data = response.json()

response = requests.post(
    "https://api.example.com/data",
    json={"key": "value"},
    headers={"Authorization": "Bearer token"}
)
// Scala - sttp (recommended)
import sttp.client3._
import sttp.client3.circe._
import io.circe.generic.auto._

val backend = HttpURLConnectionBackend()

val response = basicRequest
  .get(uri"https://api.example.com/data")
  .send(backend)

val postResponse = basicRequest
  .post(uri"https://api.example.com/data")
  .body("""{"key": "value"}""")
  .header("Authorization", "Bearer token")
  .send(backend)

Logging

# Python
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

logger.debug("Debug message")
logger.info("Info message")
logger.warning("Warning message")
logger.error("Error message", exc_info=True)
// Scala - scala-logging with logback
import com.typesafe.scalalogging.LazyLogging

class MyClass extends LazyLogging {
  logger.debug("Debug message")
  logger.info("Info message")
  logger.warn("Warning message")
  logger.error("Error message", exception)
}

// Alternative: slf4j directly
import org.slf4j.LoggerFactory

val logger = LoggerFactory.getLogger(getClass)

Testing

# Python - pytest
import pytest

def test_addition():
    assert 1 + 1 == 2

@pytest.fixture
def sample_data():
    return {"key": "value"}

def test_with_fixture(sample_data):
    assert sample_data["key"] == "value"

@pytest.mark.parametrize("input,expected", [
    (1, 2),
    (2, 4),
])
def test_double(input, expected):
    assert input * 2 == expected
// Scala - ScalaTest
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class MySpec extends AnyFlatSpec with Matchers {
  "Addition" should "work" in {
    1 + 1 shouldEqual 2
  }

  it should "handle negative numbers" in {
    -1 + 1 shouldEqual 0
  }
}

// Table-driven tests
import org.scalatest.prop.TableDrivenPropertyChecks._

val examples = Table(
  ("input", "expected"),
  (1, 2),
  (2, 4)
)

forAll(examples) { (input, expected) =>
  input * 2 shouldEqual expected
}

// Scala - munit (simpler alternative)
class MySuite extends munit.FunSuite {
  test("addition") {
    assertEquals(1 + 1, 2)
  }
}

Async/Concurrent Operations

# Python
import asyncio

async def fetch_data(url: str) -> str:
    # async HTTP call
    await asyncio.sleep(1)
    return "data"

async def main():
    results = await asyncio.gather(
        fetch_data("url1"),
        fetch_data("url2"),
    )
// Scala - Future (standard)
import scala.concurrent.{Future, ExecutionContext}
import scala.concurrent.ExecutionContext.Implicits.global

def fetchData(url: String): Future[String] = Future {
  Thread.sleep(1000)
  "data"
}

val results: Future[List[String]] = Future.sequence(List(
  fetchData("url1"),
  fetchData("url2")
))

// Scala - cats-effect IO (preferred for FP)
import cats.effect.IO
import cats.syntax.parallel._

def fetchData(url: String): IO[String] = IO.sleep(1.second) *> IO.pure("data")

val results: IO[List[String]] = List(
  fetchData("url1"),
  fetchData("url2")
).parSequence

Configuration

# Python
import os
from dataclasses import dataclass

@dataclass
class Config:
    db_host: str = os.getenv("DB_HOST", "localhost")
    db_port: int = int(os.getenv("DB_PORT", "5432"))
// Scala - pureconfig
import pureconfig._
import pureconfig.generic.auto._

case class Config(dbHost: String, dbPort: Int)

val config = ConfigSource.default.loadOrThrow[Config]

// application.conf (HOCON format)
// db-host = "localhost"
// db-host = ${?DB_HOST}
// db-port = 5432

Command Line Arguments

# Python
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--name", required=True)
parser.add_argument("--count", type=int, default=1)
args = parser.parse_args()
// Scala - scopt
import scopt.OParser

case class Config(name: String = "", count: Int = 1)

val builder = OParser.builder[Config]
val parser = {
  import builder._
  OParser.sequence(
    opt[String]("name").required().action((x, c) => c.copy(name = x)),
    opt[Int]("count").action((x, c) => c.copy(count = x))
  )
}

OParser.parse(parser, args, Config()) match {
  case Some(config) => // use config
  case None => // arguments are bad
}

// Scala - decline (FP style)
import com.monovore.decline._

val nameOpt = Opts.option[String]("name", "Name")
val countOpt = Opts.option[Int]("count", "Count").withDefault(1)

val command = Command("app", "Description") {
  (nameOpt, countOpt).tupled
}

Build Tools Comparison

PythonScala
pip/poetrysbt/mill
requirements.txtbuild.sbt
pyproject.tomlbuild.sbt
setup.pybuild.sbt
virtualenvProject-local dependencies (automatic)

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Analyze SEC 13F filings to summarize a fund’s holdings and assets under management for a quarter, compare holdings across two quarters, and rank funds by the reported value of a stock position.

中文简介正在准备中。当前显示英语简介。

  • Summarizing a fund’s holdings for one quarter
  • Comparing a fund’s reported positions across quarters
  • Finding funds with the largest reported position in a stock
benchflow-ai/skillsbench18722026年10月24日 更新

Compute active and reactive power flows at both ends of an AC power line, accounting for transformer tap ratios and phase shifts. The skill also covers apparent power, bus balance aggregation, MVA limit checks, and branch loading calculations.

中文简介正在准备中。当前显示英语简介。

  • Calculate power flow in both directions across a transmission line
  • Check branch apparent power against its MVA rating
  • Calculate and report the most heavily loaded branches
benchflow-ai/skillsbench18722026年10月24日 更新

Prepare academic PDFs for blind review by removing matching identifying details before the References section. The skill focuses redaction on specific text matches, preserves references and self-citations, and checks that the saved document retains its pages and most of its text.

中文简介正在准备中。当前显示英语简介。

  • Anonymizing an academic paper for blind review
  • Removing author names and affiliations from a PDF
  • Checking a redacted paper for text loss
benchflow-ai/skillsbench18722026年10月24日 更新

Check bathroom floor plans against simplified ADA-derived geometric rules for turning space, door width and swing, toilet placement, grab bars, and lavatory knee or toe clearance. It reports rule-specific violations and suggests local, traceable layout repairs.

中文简介正在准备中。当前显示英语简介。

  • Check turning space in a bathroom plan
  • Review door width and swing clearances
  • Verify toilet and grab bar placement
benchflow-ai/skillsbench18722026年10月24日 更新

Reviews failed GitHub Actions job logs for a pull request or specific job URLs. It returns a concise summary of the likely root cause, error messages, test names, and relevant log excerpts, so you can see what needs attention.

中文简介正在准备中。当前显示英语简介。

  • Summarizing failed CI jobs for a pull request
  • Investigating an individual GitHub Actions job
  • Finding the error and related test in logs
benchflow-ai/skillsbench18722026年10月24日 更新

Extract plan-view geometry from architectural DXF files by interpreting CAD layers and geometric entities. Normalize rooms, doors, fixtures, clearances, and grab bars into consistent, machine-checkable JSON, and describe repaired geometry in a new DXF when needed.

中文简介正在准备中。当前显示英语简介。

  • Turning an architectural DXF plan into structured JSON
  • Checking room and door geometry for accessibility
  • Extracting fixture bounds and grab bar details
benchflow-ai/skillsbench18722026年10月24日 更新

查看 benchflow-ai 的全部技能

报告此技能的问题