+2 votes
by
I write a little article where I would like to show how the same code looks in different languages. To avoid accusations that one of the languages of poorly written code, I want to ask to help me translate the following sample code in D for C++ and Python. Need analog functionality 1k1.

import std.algorithm, std.stdio, std.string;
// Count words in a file using ranges.
void main()
{
auto file = File("file.txt"); // Open for reading
const wordCount = file.byLine() // Read lines
.map!split // Split into words
.map!(a => a.length) // Count words per line
.sum(); // Total word count
writeln(wordCount);
}
Here is the second code snippet (castest counts the repetition of words):
import std.stdio, std.string; 

void main() {
uint[string] dictionary;
foreach (line; File("example.txt").byLine()) {
// Break sentence into words
// Add each word in the sentence to the vocabulary
foreach (word; splitter(strip(line))) {
if (word in dictionary) continue; // Nothing to do
auto newlD = dictionary.length;
dictionary[word] = newlD;
writeln(newlD, '\t', word);
}
}
}
If you can also comment on each line.

2 Answers

0 votes
by
 
Best answer
Python
total = 0
f = open('file.txt')
for line in f.readlines():
total += len(line.split())

print total
with open('file.txt') as f:
print len(f.read().split())
+1 vote
by
The canonical code that is closer to your code than the version from Andrey :
with open('test.txt', 'r') as f:
print(sum(len(line.split()) for line in f.readlines()))
And it is just like you:
with open('test.txt', 'r') as f:
print(sum(map(len, map(str.split, f.readlines()))))

The second task:
# печатаем уникальные слова(ваш вариант с ошибкой)
with open('test.txt', 'r') as f:
for word in set(word.strip() for word in f.read().split()):
print(word)


# выводим слова и их количество(то, что вы подразумавали)
from collections import defaultdict # словарь, для которого можно указать значения по умолчанию

with open('test.txt', 'r') as f:
words = defaultdict(int) # функция, вызывающаяся для каждого нового ключа, int() возвращает 0

for word in (word.strip() for word in f.read().split()):
words[word] += 1 # можно не проверять на наличие ключа, а сразу инкрементировать, т.к. значение по умолчанию - 0

for word, num in words.items():
print(word, '\t', num)
by
Ah Yes, it's Python 3, and in the two most also
...