【问题标题】:Need to write a find/replace script for items in a text file需要为文本文件中的项目编写查找/替换脚本
【发布时间】:2011-10-25 23:44:38
【问题描述】:

我遇到了一个问题。我有一个包含数千个城市及其 gps 坐标的文本列表。格式为:

City,longitude,latitude,Parent

所以一个例子可能是:

Los Angeles,34.11N,118.41W,California 

问题是我需要 long/lat 在 + 和 - 值中,所以正确的条目是:

Los Angeles,34.11,-118.41,California

所以脚本会是这样的

  • 查找“W”或“S”(西和南得到“-”符号)

  • 如果您在第 2 个或第 3 个“,”中找到这些字母中的任何一个,请在第一个数字前插入一个“-”符号。 (我们不想影响第 1 或第 4 字段中的单词)

  • 然后从 long/lat 字段中删除任何字母。

这可以通过无数种方式完成 - excel、.bat 文件,还是其他?

如果有人能提供帮助,我将不胜感激。 谢谢

【问题讨论】:

  • 只需将数据导入 excel,因为数据似乎是 CSV,然后将一些 excel 魔术应用于正确的列...
  • 说到“excel 魔法”……我是个麻瓜。魔术需要找到字母,然后在开头插入一个符号。你知道那个公式吗?

标签: excel text batch-file replace


【解决方案1】:

试试这个批处理文件:

@echo off
setlocal EnableDelayedExpansion
if exist thefile.tmp del thefile.tmp
for /F "tokens=1-4 delims=," %%a in (thefile.txt) do (
    set longitude=%%b
    set sign=!longitude:~-1!
    set longitude=!longitude:~0,-1!
    if /I !sign! == S set longitude=-!longitude!
    set latitude=%%c
    set sign=!latitude:~-1!
    set latitude=!latitude:~0,-1!
    if /I !sign! == W set latitude=-!latitude!
    echo %%a,!longitude!,!latitude!,%%d>> thefile.tmp
)
del thefile.txt
ren thefile.tmp thefile.txt

【讨论】:

    【解决方案2】:

    以下公式应该可以帮助您入门:

    使用以下内容作为输入(注意在excel中需要将“.”转换为“,”):

    A2          B2      C2      D2
    Los Angeles 34.11N  118,41W California 
    

    这是我的瑞典版 excel

    =OM(HITTA("W";C2);-1*(BYT.UT(C2;"W";""));)
    

    我认为这可以转化为:

    =IF(FIND("W";C2);-1*(REPLACE(C2;"W";""));)
    

    这样的结果是单元格 C2 被转换为-118,41

    更新

    Excel/open office 非常适合做很多事情,但我总是发现文本处理 非常尴尬...您似乎对替代解决方案持开放态度,并且 我的建议是你安装python。看起来你在窗户上; 这里有两种获取python的方法:

    1. python.org安装python

    2. cygwin.com 安装 cygwin 并使用该 python

    alternative 2. 有一个优势,你会得到一个竞争的 unix/linux windows环境下!

    这就是(有点冗长的)python 解决方案的外观;即使也许 在您应该能够完全理解代码之前,您从未见过 python 轻松...

    #!/usr/bin/env python
    
    def convert(word):
    
        if 'W' in word or 'S' in word:
            word = word.replace('W', "")
            word = word.replace('S', "")
            word = '-' + word
        return word
    
    with open("input") as fd:
        for line in fd:
            line=line.strip()
            line = line.split(',')
            line[1] = convert(line[1])
            line[2] = convert(line[2])
            print ",".join(line)
    

    【讨论】:

    • 嗯,我似乎遇到了 511 错误。我应该指出我使用的是开放式办公室而不是 Excel。我看看能不能找到excel...
    • 是的,代码看起来不错 - 我可以看到它的意图。请不要笑 - 但我不能在 python 中完全“打开文件”对吗?我想有一行代码来指定文本文档?如果您有一个文件位于 user/myusername/downloads 中,而 python 位于 /usr/local/bin/pythonw 中,那么终端的确切行可能是什么?现在我在一个mac上。我可能在电脑上,可能。谢谢
    • 将shebang更改为#!/usr/local/bin/pythonw并使用with open("/user/myusername/downloads/file.txt") as fd:然后使用chmod u+x name_of_script使文件可执行并使用./name_of_script执行它
    猜你喜欢
    • 2013-06-21
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 2013-03-31
    相关资源
    最近更新 更多