@beduin01

Как перевести этот пример на С++ и Python?

Я пишу небольшую статью, где хотелось бы показать как один и тот же же код выглядит на разных языках. Чтобы избежать упреков в том, что на одном языков код криво написан, я хочу попросить помочь мне перевести следующий пример кода на D на С++ и Python. Нужен аналог по функционалу 1к1.

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);
}


Вот второй фрагмент кода (подсчитывает частость повторения слов):
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);
        }
    }
}


Если можно так же прокомментируйте каждую строку.
  • Вопрос задан
  • 1433 просмотра
Решения вопроса 2
mututunus
@mututunus
Backend developer (Python, Golang)
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())
Ответ написан
AtomKrieg
@AtomKrieg
Давай я поищу в Google за тебя
У вас ошибка в описании второй программы на D: она не подсчитывает частотность. Она выводит все уникальные слова.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
	unsigned sum = 0;
	ifstream file ("file.txt");

	for (string word; file >> word;)
		++sum;

	cout << sum << endl;

	return 0;
}


#include <iostream>
#include <fstream>
#include <string>
#include <set>

using namespace std;

int main()
{
	set<string> unique_words;
	ifstream file ("file.txt");
	
	for (string word; file >> word;)
		unique_words.insert(word);
	
	for (auto& word: unique_words)
		cout << word << endl;

	return 0;
}
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
angru
@angru
Каноничный код, ближе к вашему коду, чем в варианте от Andrey:
with open('test.txt', 'r') as f:
    print(sum(len(line.split()) for line in f.readlines()))

А это прям совсем как у вас:
with open('test.txt', 'r') as f:
    print(sum(map(len, map(str.split, f.readlines()))))


Вторая задача:
# печатаем уникальные слова(ваш вариант с ошибкой)
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)
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
19 апр. 2024, в 05:01
999999 руб./за проект
19 апр. 2024, в 03:52
1000 руб./за проект
19 апр. 2024, в 03:01
1000 руб./за проект