通过拆分获取字符串中的日期

0 投票
3 回答
4817 浏览
提问于 2025-04-18 07:39

我有一批原始文本文件。每个文件的开头都是这样的格式:Date>>month.day year News garbage

这里的garbage是我不需要的一大堆文字,长度各不相同。而Date>>News的位置是固定的,不会改变。

我想把month day year这部分内容提取出来,放到一个CSV文件里,每个文件对应一行,格式是day month year

我该如何把month day year分别复制到不同的变量里呢?

我试过在已知的单词后面和前面分割字符串。我对字符串切片(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.

3 个回答

0

你可以使用字符串的分割方法:

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

或者你可以使用正则表达式(我看到你引入了这个,但没有使用)来处理分组。我不记得具体的语法了,但大概是这样的:r'(.*)(Date>>)(.*)。这个正则表达式会在两个其他字符串之间寻找“Date>>”这个字符串。括号的作用是把找到的内容分成不同的组,方便后续使用。

1

你可以使用字符串的方法 .split(" ") 来把输出结果按空格分开,变成一个变量列表。因为年份和月份.日期总是会在同一个位置,所以你可以通过它们在列表中的位置来访问它们。要把月份和日期分开,可以再用一次 .split 方法,不过这次是用 . 作为分隔符。

举个例子:

list = theString.split(" ")
year = list[1]
month= list[0].split(".")[0]
day = list[0].split(".")[1]
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

编辑:

其实,还有一个更好的(我觉得)解决方案,使用 re.split,这个方法在 Robin 提到的链接 中有描述。用这种方法你可以这样做:

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

撰写回答