Board logo

标题: [文本处理] [已解决]请教批处理怎么查询对应关系? [打印本页]

作者: newgain    时间: 2021-6-3 21:46     标题: [已解决]请教批处理怎么查询对应关系?

假如有如下文本
1 北京
2 天津
3 上海
4 武汉
5 苏州
6 沈阳
7 南京
8 广州
…………
类似对应大概40组

请教怎么做可以输入前面的数字 ECHO出后面的地址?
作者: jonnywang    时间: 2021-6-3 22:23

@echo off&chcp 65001&color f0
set file=test.txt
for /f "tokens=1-2" %%a in (%file%) do echo %%a %%b
set /p in=输入对应的号码:
for /f "tokens=1-2" %%a in (%file%) do (
if "%in%"=="%%a" echo %%b
)
pause
作者: smss    时间: 2021-6-3 22:39

  1. @Echo off&SetLocal EnableDelayedExpansion
  2. for %%i in (北京 天津 上海 武汉 苏州 沈阳南京 广州)do call set "T%%n%%=%%i"&set /a n+=1
  3. choice /c:12345678 /m:"输入数字:"
  4. echo !T%errorlevel%!
  5. pause
复制代码

作者: newgain    时间: 2021-6-3 23:41

@echo off&chcp 65001&color f0
set file=test.txt
for /f "tokens=1-2" %%a in (%file%) do echo %%a %% ...
jonnywang 发表于 2021-6-3 22:23

麻烦问下我删除set file=test.txt 把%%a in (%file%) 改成%%a in (test.txt) 可以么?目前没发现区别。
另外 echo %%a %%b 会吧所有地址全部输出到批处理上部,后面加了>Nul
作者: newgain    时间: 2021-6-3 23:42

@echo off&chcp 65001&color f0
set file=test.txt
for /f "tokens=1-2" %%a in (%file%) do echo %%a %% ...
jonnywang 发表于 2021-6-3 22:23





  
  1. @echo off&chcp 65001&color f0
  2. for /f "tokens=1-2" %%a in (test.txt) do echo %%a %%b>nul
  3. set /p in=输入对应的号码:
  4. for /f "tokens=1-2" %%a in (test.txt) do (
  5. if "%in%"=="%%a" echo %%b
  6. )
  7. pause
复制代码

作者: jonnywang    时间: 2021-6-3 23:54

可以的,习惯而已。另外你加了nul就不显示了,如果你不想在批处理上面显示出来的话,那段话直接可以删除,不用加nul。和后面的for语句不冲突。
作者: qixiaobin0715    时间: 2021-6-4 06:18

  1. @echo off
  2. set /p var=请输入:
  3. for /f "tokens=1*" %%i in ('findstr /b /c:"%var% " test.txt') do echo,%%j
  4. pause
复制代码

作者: wxyz0001    时间: 2021-6-4 12:00

用Python写的
  1. with open('city.txt', 'r', encoding='gbk') as f:
  2.     lines = f.readlines()
  3.     city_dict = {line.split(' ')[0]: line.split(' ')[1].strip('\n') for line in lines if line.find(' ') != -1}
  4.     while True:
  5.         key = input('请输入城市的索引(输入0退出):')
  6.         if key == '0':
  7.             break
  8.         print('索引对应的城市为:', city_dict[key])
复制代码

作者: Gin_Q    时间: 2021-6-4 13:12

  1. @echo off
  2. SetLocal EnableDelayedExpansion
  3. set "dict="
  4. for /f "tokens=1-2" %%L in ('type 1.txt') do (
  5.     set "dict%%L=%%M")
  6. set /p input="请输入序号"
  7. echo !dict%input%!
  8. pause
复制代码





欢迎光临 批处理之家 (http://bbs.bathome.net/) Powered by Discuz! 7.2