Как рассматривать первую строку файла по-другому в Python?

Для приложения WinForm я продолжал работать, мы могли определить regex на допустимых символах, которые будут работать на каждом нажатии клавиши и проверке для текста для любых текстовых полей (приложение ввода данных), таким образом, я использовал кэш или скомпилировал regexes такой как

  private static Dictionary<string, Regex> regexCache = new Dictionary<string, Regex>(20);

, Где regex выражение было ключом.

Тогда у меня была статическая функция, которую я мог вызвать при проверке данных:

public static bool RegExValidate(string text, string regex)
{
  if (!regexCache.ContainsKey(regex))
  {
    Regex compiledRegex = new Regex(regex,RegexOptions.Compiled);
    regexCache.Add(regex, compiledRegex);
  }
  return regexCache[regex].IsMatch(text);
}
9
задан SilentGhost 4 December 2009 в 13:23
поделиться

4 ответа

You could:

processHeader(f.readline())
for line in f:
    processBody(line)
16
ответ дан 4 December 2019 в 07:35
поделиться
f = file("test")
processHeader(f.next()) #or next(f) for py3
for line in f:
    processBody(line)

This works.

Edit:

Changed .__next__ to next (they are equivalent, but I suppose next is more concise).

Regaring file vs open, file just seems more clear to me, therefore I will continue to prefer it over open.

8
ответ дан 4 December 2019 в 07:35
поделиться

Use iter()

it_f = iter(f)
header = it_f.next()
processHeader(header)

for line in it_f:
    processBody(line)

It works with any iterable object.

3
ответ дан 4 December 2019 в 07:35
поделиться

Large text files with headers in the first line? So it's tabular data.

Just to make sure: Have you looked at the csv module? It should handle all tabular data except such where the fields are not delimited but defined by position. And it does the header stuff too.

2
ответ дан 4 December 2019 в 07:35
поделиться
Другие вопросы по тегам:

Похожие вопросы: