【问题标题】:Get date from string by splitting通过拆分从字符串中获取日期
【发布时间】:2014-05-27 02:38:45
【问题描述】:

我有一批原始文本文件。每个文件都以Date>>month.day year News garbage开头。

garbage 是一大堆我不需要的文本,而且长度各不相同。 Date>>News 这两个词总是出现在同一个地方,不会改变。

我想复制月日年并将此数据插入到 CSV 文件中,每个文件都有一个新行,格式为 日月年

如何将月日年复制到单独的变量中?

我尝试在已知单词之后和已知单词之前拆分字符串。我对 string[x:y] 很熟悉,但我基本上想将 x 和 y 从数字更改为实际单词(即 string[Date>>:News])

import re, os, sys, fnmatch, csv
folder = raw_input('Drag and drop the folder > ')
for filename in os.listdir(folder):
# First, avoid system files
if filename.startswith("."):
    pass
else:
    # Tell the script the file is in this directory and can be written
    file = open(folder+'/'+filename, "r+")
    filecontents = file.read()
    thestring = str(filecontents)
    print thestring[9:20]

一个示例文本文件:

Date>>January 2. 2012 News 122

5 different news agencies have reported the story of a man washing his dog.

【问题讨论】:

标签: python string split word


【解决方案1】:

这是使用re 模块的解决方案:

import re

s = "Date>>January 2. 2012 News 122"
m = re.match("^Date>>(\S+)\s+(\d+)\.\s+(\d+)", s)
if m:
   month, day, year = m.groups()
   print("{} {} {}").format(month, day, year)

输出:

January 2 2012

编辑:

实际上,link Robin posted 中描述了另一个使用 re.split 的更好 (imo) 解决方案。使用这种方法,您可以这样做:

month, day, year = re.split(">>| |\. ", s)[1:4]

【讨论】:

    【解决方案2】:

    您可以使用字符串方法 .split(" ") 将输出分隔为在空格字符处拆分的变量列表。因为 year 和 month.day 总是在同一个地方,你可以通过它们在输出列表中的位置来访问它们。要分隔月份和日期,请再次使用 .split 函数,但这次是 .

    例子:

    list = theString.split(" ")
    year = list[1]
    month= list[0].split(".")[0]
    day = list[0].split(".")[1]
    

    【讨论】:

    • 虽然不应该使用list这个词,否则我会怎么做。
    • 另外,你需要处理'Date>>'
    【解决方案3】:

    你可以使用 string.split:

    x = "A b c"
    x.split(" ")
    

    或者您可以对组使用正则表达式(我看到您导入但不使用)。我不记得确切的语法,但它类似于r'(.*)(Date>>)(.*)。这将在任何其他类型的两个字符串之间搜索字符串“Date>>”。括号会将它们捕获到编号的组中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-28
      • 2021-05-10
      • 1970-01-01
      相关资源
      最近更新 更多